verify = async (jwt) => {
    this._requireConfigured()
    invariant(jwt, `'jwt' must be provided`)

    await axios.post(`${this.host}/api/verify`, { token: jwt })
  }
Example #2
0
  injectDOMPropertyConfig: function(domPropertyConfig) {
    var Properties = domPropertyConfig.Properties || {};
    var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {};
    var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {};
    var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {};

    if (domPropertyConfig.isCustomAttribute) {
      DOMProperty._isCustomAttributeFunctions.push(
        domPropertyConfig.isCustomAttribute
      );
    }

    for (var propName in Properties) {
      invariant(
        !DOMProperty.isStandardName[propName],
        'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' +
        '\'%s\' which has already been injected. You may be accidentally ' +
        'injecting the same DOM property config twice, or you may be ' +
        'injecting two configs that have conflicting property names.',
        propName
      );

      DOMProperty.isStandardName[propName] = true;

      var lowerCased = propName.toLowerCase();
      DOMProperty.getPossibleStandardName[lowerCased] = propName;

      var attributeName = DOMAttributeNames[propName];
      if (attributeName) {
        DOMProperty.getPossibleStandardName[attributeName] = propName;
      }

      DOMProperty.getAttributeName[propName] = attributeName || lowerCased;

      DOMProperty.getPropertyName[propName] =
        DOMPropertyNames[propName] || propName;

      var mutationMethod = DOMMutationMethods[propName];
      if (mutationMethod) {
        DOMProperty.getMutationMethod[propName] = mutationMethod;
      }

      var propConfig = Properties[propName];
      DOMProperty.mustUseAttribute[propName] =
        propConfig & DOMPropertyInjection.MUST_USE_ATTRIBUTE;
      DOMProperty.mustUseProperty[propName] =
        propConfig & DOMPropertyInjection.MUST_USE_PROPERTY;
      DOMProperty.hasSideEffects[propName] =
        propConfig & DOMPropertyInjection.HAS_SIDE_EFFECTS;
      DOMProperty.hasBooleanValue[propName] =
        propConfig & DOMPropertyInjection.HAS_BOOLEAN_VALUE;
      DOMProperty.hasNumericValue[propName] =
        propConfig & DOMPropertyInjection.HAS_NUMERIC_VALUE;
      DOMProperty.hasPositiveNumericValue[propName] =
        propConfig & DOMPropertyInjection.HAS_POSITIVE_NUMERIC_VALUE;
      DOMProperty.hasOverloadedBooleanValue[propName] =
        propConfig & DOMPropertyInjection.HAS_OVERLOADED_BOOLEAN_VALUE;

      invariant(
        !DOMProperty.mustUseAttribute[propName] ||
          !DOMProperty.mustUseProperty[propName],
        'DOMProperty: Cannot require using both attribute and property: %s',
        propName
      );
      invariant(
        DOMProperty.mustUseProperty[propName] ||
          !DOMProperty.hasSideEffects[propName],
        'DOMProperty: Properties that have side effects must use property: %s',
        propName
      );
      invariant(
        !!DOMProperty.hasBooleanValue[propName] +
          !!DOMProperty.hasNumericValue[propName] +
          !!DOMProperty.hasOverloadedBooleanValue[propName] <= 1,
        'DOMProperty: Value can be one of boolean, overloaded boolean, or ' +
        'numeric value, but not a combination: %s',
        propName
      );
    }
  }
  render: function() {
    var format         = this.props.children;
    var parent         = this.props.component;
    var unsafe         = this.props.unsafe === true;
    var interpolations = extend({}, this.props, this.props.with);
    var props          = except(this.props, OMITTED_PROPS);

    var matches = [];
    var children = [];

    if (!isString(format)) {
      format = this.props.format;
    }

    invariant(isString(format), 'Interpolate expects either a format string as only child or a `format` prop with a string value');

    if (unsafe) {
      var content = format.split(REGEXP).reduce(function(memo, match, index) {
        var html;

        if (index % 2 === 0) {
          html = match;
        } else {
          html = interpolations[match];
          matches.push(match);
        }

        if (React.isValidElement(html)) {
          throw new Error('cannot interpolate a React component into unsafe text');
        }

        memo += html;

        return memo;
      }, '');

      props.dangerouslySetInnerHTML = { __html: content };
    } else {
      format.split(REGEXP).reduce(function(memo, match, index) {
        var child;

        if (index % 2 === 0) {
          if (match.length === 0) {
            return memo;
          }

          child = match;
        } else {
          child = interpolations[match];
          matches.push(match);
        }

        memo.push(child);

        return memo;
      }, children);
    }

    props = except(props, matches);

    return React.createElement.apply(this, [parent, props].concat(children));
  }
Example #4
0
  findComponentRoot: function(ancestorNode, targetID) {
    var firstChildren = findComponentRootReusableArray;
    var childIndex = 0;

    var deepestAncestor = findDeepestCachedAncestor(targetID) || ancestorNode;

    firstChildren[0] = deepestAncestor.firstChild;
    firstChildren.length = 1;

    while (childIndex < firstChildren.length) {
      var child = firstChildren[childIndex++];
      var targetChild;

      while (child) {
        var childID = ReactMount.getID(child);
        if (childID) {
          // Even if we find the node we're looking for, we finish looping
          // through its siblings to ensure they're cached so that we don't have
          // to revisit this node again. Otherwise, we make n^2 calls to getID
          // when visiting the many children of a single node in order.

          if (targetID === childID) {
            targetChild = child;
          } else if (ReactInstanceHandles.isAncestorIDOf(childID, targetID)) {
            // If we find a child whose ID is an ancestor of the given ID,
            // then we can be sure that we only want to search the subtree
            // rooted at this child, so we can throw out the rest of the
            // search state.
            firstChildren.length = childIndex = 0;
            firstChildren.push(child.firstChild);
          }

        } else {
          // If this child had no ID, then there's a chance that it was
          // injected automatically by the browser, as when a `<table>`
          // element sprouts an extra `<tbody>` child as a side effect of
          // `.innerHTML` parsing. Optimistically continue down this
          // branch, but not before examining the other siblings.
          firstChildren.push(child.firstChild);
        }

        child = child.nextSibling;
      }

      if (targetChild) {
        // Emptying firstChildren/findComponentRootReusableArray is
        // not necessary for correctness, but it helps the GC reclaim
        // any nodes that were left at the end of the search.
        firstChildren.length = 0;

        return targetChild;
      }
    }

    firstChildren.length = 0;

    invariant(
      false,
      'findComponentRoot(..., %s): Unable to find element. This probably ' +
      'means the DOM was unexpectedly mutated (e.g., by the browser), ' +
      'usually due to forgetting a <tbody> when using tables, nesting tags ' +
      'like <form>, <p>, or <a>, or using non-SVG elements in an <svg> ' +
      'parent. ' +
      'Try inspecting the child nodes of the element with React ID `%s`.',
      targetID,
      ReactMount.getID(ancestorNode)
    );
  },
Example #5
0
  /**
   * Update a connection with newly fetched edges.
   */
  _writeEdges(
    connection: RelayQuery.Field,
    edges: RelayQuery.Field,
    state: WriterState
  ): void {
    const {
      recordID: connectionID,
      responseData: connectionData,
    } = state;
    invariant(
      typeof connectionData === 'object' && connectionData !== null,
      'RelayQueryWriter: Cannot write edges for malformed connection `%s` on ' +
      'record `%s`, expected the response to be an object.',
      connection.getDebugName(),
      connectionID
    );
    const edgesData = connectionData[EDGES];

    // Validate response data.
    if (edgesData == null) {
      warning(
        false,
        'RelayQueryWriter: Cannot write edges for connection `%s` on record ' +
        '`%s`, expected a response for field `edges`.',
        connection.getDebugName(),
        connectionID
      );
      return;
    }
    invariant(
      Array.isArray(edgesData),
      'RelayQueryWriter: Cannot write edges for connection `%s` on record ' +
      '`%s`, expected `edges` to be an array.',
      connection.getDebugName(),
      connectionID
    );

    const rangeCalls = connection.getCallsWithValues();
    invariant(
      RelayConnectionInterface.hasRangeCalls(rangeCalls),
      'RelayQueryWriter: Cannot write edges for connection on record ' +
      '`%s` without `first`, `last`, or `find` argument.',
      connectionID
    );
    const rangeInfo = this._store.getRangeMetadata(
      connectionID,
      rangeCalls
    );
    invariant(
      rangeInfo,
      'RelayQueryWriter: Expected a range to exist for connection field `%s` ' +
      'on record `%s`.',
      connection.getDebugName(),
      connectionID
    );
    const fetchedEdgeIDs = [];
    const filteredEdges = rangeInfo.filteredEdges;
    let isUpdate = false;
    let nextIndex = 0;
    // Traverse connection edges, reusing existing edges if they exist
    edgesData.forEach(edgeData => {
      // validate response data
      if (edgeData == null) {
        return;
      }
      invariant(
        typeof edgeData === 'object' && edgeData,
        'RelayQueryWriter: Cannot write edge for connection field `%s` on ' +
        'record `%s`, expected an object.',
        connection.getDebugName(),
        connectionID
      );

      const nodeData = edgeData[NODE];
      if (nodeData == null) {
        return;
      }

      invariant(
        typeof nodeData === 'object',
        'RelayQueryWriter: Expected node to be an object for field `%s` on ' +
        'record `%s`.',
        connection.getDebugName(),
        connectionID
      );

      // For consistency, edge IDs are calculated from the connection & node ID.
      // A node ID is only generated if the node does not have an id and
      // there is no existing edge.
      const prevEdge = filteredEdges[nextIndex++];
      const nodeID = (
        (nodeData && nodeData[ID]) ||
        (prevEdge && this._store.getLinkedRecordID(prevEdge.edgeID, NODE)) ||
        generateClientID()
      );
      // TODO: Flow: `nodeID` is `string`
      const edgeID = generateClientEdgeID(connectionID, nodeID);
      const path = RelayQueryPath.getPath(state.path, edges, edgeID);
      this.createRecordIfMissing(edges, edgeID, path, null);
      fetchedEdgeIDs.push(edgeID);

      // Write data for the edge, using `nodeID` as the id for direct descendant
      // `node` fields. This is necessary for `node`s that do not have an `id`,
      // which would cause the generated ID here to not match the ID generated
      // in `_writeLink`.
      this.traverse(edges, {
        nodeID,
        path,
        recordID: edgeID,
        responseData: edgeData,
      });
      isUpdate = isUpdate || !prevEdge || edgeID !== prevEdge.edgeID;
    });

    const pageInfo = connectionData[PAGE_INFO] ||
      RelayConnectionInterface.getDefaultPageInfo();
    this._writer.putRangeEdges(
      connectionID,
      rangeCalls,
      pageInfo,
      fetchedEdgeIDs
    );

    // Only broadcast an update to the range if an edge was added/changed.
    // Node-level changes will broadcast at the node ID.
    if (isUpdate) {
      this.recordUpdate(connectionID);
    }
  }
Example #6
0
import invariant from 'invariant';
import { Store, setHandlers } from 'shared/model/toasts';

import * as lms from '../components/toasts/lms';
import * as scores from '../components/toasts/scores';
import Reload from '../components/toasts/reload';

const JobToasts = { lms, scores };

setHandlers({
  job(toast) {
    invariant(['ok', 'failed'].includes(toast.status), 'job status must be ok or failed');
    return JobToasts[toast.type][toast.status == 'ok' ? 'Success' : 'Failure'];
  },
  reload() {
    return Reload;
  },
});

export { Toast } from 'shared/model/toasts';

export default Store;
Example #7
0
/**
 * Create a handler for OAuth 2.0.
 *
 * @param  {Object} scheme
 * @param  {Object} opts
 * @param  {String} key
 * @return {Object}
 */
function createOAuth2Handler (scheme, opts, key) {
  var app = router()
  var server = oauth2orize.createServer()
  var settings = scheme.settings
  var options = extend({ grant: {}, exchange: {} }, opts)
  var scopes = arrify(scheme.settings.scopes)

  var BASIC_KEY = 'osprey:' + key + ':basic'
  var CLIENT_PASSWORD_KEY = 'osprey:' + key + 'oauth2-client-password'
  var BEARER_KEY = 'osprey:' + key + ':bearer'

  invariant(
    settings.authorizationGrants && settings.authorizationGrants.length > 0,
    'RAML "authorizationGrants" must specify supported grant types'
  )

  invariant(
    typeof options.findUserByToken === 'function',
    'Option "findUserByToken" must be a function: %s',
    'https://github.com/jaredhanson/passport-http-bearer#configure-strategy'
  )

  invariant(
    typeof options.authenticateClient === 'function',
    'Option "authenticateClient" must be a function: %s',
    'https://github.com/jaredhanson/passport-oauth2-client-password#configure-strategy'
  )

  // Set up passport for authentication.
  passport.use(BASIC_KEY, new BasicStrategy(options.authenticateClient))
  passport.use(CLIENT_PASSWORD_KEY, new ClientPasswordStrategy(options.authenticateClient))
  passport.use(BEARER_KEY, new BearerStrategy(options.findUserByToken))

  var accessTokenUri = parse(options.accessTokenUri || settings.accessTokenUri).path

  // Body parsing middleware for OAuth 2.0 routes.
  var parseBody = [bodyParser.json(), bodyParser.urlencoded({ extended: false })]

  invariant(
    validPathEnding(settings.accessTokenUri, accessTokenUri),
    '`accessTokenUri` must match the suffix of the RAML `accessTokenUri` setting'
  )

  // Skip authorization page logic if not required.
  if (
    settings.authorizationGrants.indexOf('code') > -1 ||
    settings.authorizationGrants.indexOf('token') > -1
  ) {
    var serializeClient = options.serializeClient
    var deserializeClient = options.deserializeClient
    var sessionKeys = options.sessionKeys
    var ensureLoggedIn = options.ensureLoggedIn
    var authorizeClient = options.authorizeClient
    var serveAuthorizationPage = options.serveAuthorizationPage
    var immediateAuthorization = options.immediateAuthorization
    var authorizationUri = parse(options.authorizationUri || settings.authorizationUri).path

    invariant(
      validPathEnding(settings.authorizationUri, authorizationUri),
      '`authorizationUri` must match the suffix of the RAML `authorizationUri` setting'
    )

    invariant(
      typeof serializeClient === 'function',
      'Option "serializeClient" must be a function: %s',
      'https://github.com/jaredhanson/oauth2orize#session-serialization'
    )

    invariant(
      typeof deserializeClient === 'function',
      'Option "deserializeClient" must be a function: %s',
      'https://github.com/jaredhanson/oauth2orize#session-serialization'
    )

    invariant(
      Array.isArray(sessionKeys) && sessionKeys.length > 0,
      'Options "sessionKeys" must be an array: %s',
      'https://github.com/expressjs/cookie-session#keys'
    )

    invariant(
      typeof authorizeClient === 'function',
      'Option "authorizeClient" must be a function: %s',
      'https://github.com/jaredhanson/oauth2orize#implement-authorization-endpoint'
    )

    invariant(
      typeof serveAuthorizationPage === 'function',
      'Option "serveAuthorizationPage" must be a middleware function that ' +
      'serves the authorization dialog page'
    )

    invariant(
      typeof ensureLoggedIn === 'function',
      'Option "ensureLoggedIn" must be a middleware function that handles ' +
      'when the user is logged out'
    )

    server.serializeClient(serializeClient)
    server.deserializeClient(deserializeClient)

    // Create session middleware for Passport to work properly.
    var session = cookieSession({
      name: 'osprey-' + key,
      keys: options.sessionKeys
    })

    // Authorize client validation.
    var validate = function (clientId, redirectUri, scope, type, done) {
      validateScope(scopes, scope)

      return authorizeClient(clientId, redirectUri, scope, type, done)
    }

    // Set up immediate function. Wrap it for consistent arity.
    var immediate = immediateAuthorization ? function (client, user, scope, done) {
      // Custom callback for scope injection.
      function cb (err, validated) {
        return done(err, validated, { scope: scope })
      }

      return immediateAuthorization(client, user, scope, cb)
    } : null

    // Mount authorization page. DO NOT ENABLE CORS BEFORE THIS ROUTE!
    app.get(
      authorizationUri,
      session,
      ensureLoggedIn,
      attachQuery,
      attachRedirect,
      server.authorize(validate, immediate),
      serveAuthorizationPage
    )

    // Page to POST form to for authorization.
    app.post(
      authorizationUri,
      session,
      ensureLoggedIn,
      parseBody,
      attachRedirect,
      server.decision(function (req, done) {
        return done(null, {
          scope: req.body.scope || []
        })
      })
    )
  }

  // Mount the access token endpoint.
  app.post(
    accessTokenUri,
    parseBody,
    passport.initialize(),
    passport.authenticate([BASIC_KEY, CLIENT_PASSWORD_KEY], { session: false }),
    server.token()
  )

  settings.authorizationGrants.forEach(function (grantType) {
    var grant = options.grant[grantType]
    var exchange = options.exchange[grantType]

    if (grantType === 'code') {
      invariant(
        typeof grant === 'function',
        'Option "grant.code" must be a function: %s',
        'https://github.com/jaredhanson/oauth2orize#register-grants'
      )

      invariant(
        typeof exchange === 'function',
        'Option "exchange.code" must be a function: %s',
        'https://github.com/jaredhanson/oauth2orize#register-exchanges'
      )

      server.grant(oauth2orize.grant.code(function (client, redirectUri, user, ares, done) {
        validateScope(scopes, ares.scope)

        return grant(client, redirectUri, user, ares, done)
      }))

      server.exchange(oauth2orize.exchange.code(exchange))

      return
    }

    if (grantType === 'token') {
      invariant(
        typeof grant === 'function',
        'Option "grant.token" must be a function: %s',
        'https://github.com/jaredhanson/oauth2orize#register-grants'
      )

      server.grant(oauth2orize.grant.token(function (client, user, ares, done) {
        validateScope(scopes, ares.scope)

        return grant(client, user, ares, done)
      }))

      return
    }

    if (grantType === 'owner') {
      invariant(
        typeof exchange === 'function',
        'Option "exchange.owner" must be a function: %s',
        'https://github.com/jaredhanson/oauth2orize#register-grants'
      )

      server.exchange(oauth2orize.exchange.password(function (client, username, password, scope, done) {
        validateScope(scopes, scope)

        return exchange(client, username, password, scope, done)
      }))

      return
    }

    if (grantType === 'credentials') {
      invariant(
        typeof exchange === 'function',
        'Option "exchange.credentials" must be a function: %s',
        'https://github.com/jaredhanson/oauth2orize#register-grants'
      )

      server.exchange(oauth2orize.exchange.clientCredentials(function (client, scope, done) {
        validateScope(scopes, scope)

        return exchange(client, scope, done)
      }))

      return
    }

    throw new TypeError('Unknown grant "' + key + '" type: ' + grantType)
  })

  var refreshToken = options.exchange.refresh

  // Refresh tokens are optional.
  if (typeof refreshToken === 'function') {
    server.exchange(oauth2orize.exchange.refreshToken(refreshToken))
  }

  var authenticate = [
    passport.initialize(),
    passport.authenticate(BEARER_KEY, { session: false, failWithError: true })
  ]

  /**
   * OAuth 2.0 authentication handler creator.
   *
   * @param  {Object}   options
   * @return {Function}
   */
  function handler (options) {
    if (!options) {
      return authenticate
    }

    // Return with scope validation.
    return authenticate.concat(scope(options.scopes))
  }

  return { router: app, handler: handler }
}
Example #8
0
function validateMutationConfig(
  config: RelayMutationConfig,
  name: string,
): void {
  function assertValid(properties: PropertyDescription): void {
    // Check for unexpected properties.
    Object.keys(config).forEach(property => {
      if (property === 'type') {
        return;
      }

      if (!properties.hasOwnProperty(property)) {
        const message = sprintf(
          'validateMutationConfig: Unexpected key `%s` in `%s` config ' +
          'for `%s`',
          property,
          config.type,
          name
        );
        const suggestion = Object.keys(properties).find(
          candidate => testEditDistance(candidate, property, FUZZY_THRESHOLD)
        );
        if (suggestion) {
          invariant(false, '%s; did you mean `%s`?', message, suggestion);
        } else {
          /* eslint-disable fb-www/sprintf-like-args-uniqueness */
          invariant(false, '%s.', message);
          /* eslint-enable fb-www/sprintf-like-args-uniqueness */
        }
      }
    });

    // Check for deprecated and missing properties.
    Object.keys(properties).forEach(property => {
      const validator = properties[property];
      const isRequired = validator.type === 'REQUIRED';
      const isDeprecated = validator.type === 'DEPRECATED';
      const present = config.hasOwnProperty(property);
      if (
        isRequired && !present ||
        isDeprecated && present
      ) {
        validator.assert(
          false,
          'validateMutationConfig: `%s` config on `%s` %s `%s`.',
          config.type,
          name,
          validator.message,
          property
        );
      }
    });
  }

  switch (config.type) {
    case 'FIELDS_CHANGE':
      assertValid({
        fieldIDs: REQUIRED,
      });
      break;

    case 'RANGE_ADD':
      assertValid({
        connectionName: REQUIRED,
        edgeName: REQUIRED,
        parentID: OPTIONAL,
        parentName: OPTIONAL,
        rangeBehaviors: REQUIRED,
      });
      break;

    case 'NODE_DELETE':
      assertValid({
        connectionName: REQUIRED,
        deletedIDFieldName: REQUIRED,
        parentID: OPTIONAL,
        parentName: REQUIRED,
      });
      break;

    case 'RANGE_DELETE':
      assertValid({
        connectionName: REQUIRED,
        deletedIDFieldName: REQUIRED,
        parentID: OPTIONAL,
        parentName: REQUIRED,
        pathToConnection: REQUIRED,
      });
      break;

    case 'REQUIRED_CHILDREN':
      assertValid({
        children: REQUIRED,
      });
      break;

    default:
      invariant(
        false,
        'validateMutationConfig: unknown config type `%s` on `%s`',
        config.type,
        name,
      );
  }
}
export function defaultStackRouteReducer(
  state: EnhancedNavigationRoute,
  action: NavigationAction,
): EnhancedNavigationRoute {
  invariant(
    state.type === STACK_ROUTE,
    '`%s` is configured with an invalid reducer.',
    state.type
  );

  const { nextNavigationState: nextState } = action;

  // `creteState()` always returns a unary tree
  const nextLeaf = nextState.routes[0];

  if (!nextLeaf) {
    // Return `nextState` to reset state, or `state` to maintain state
    return nextState;
  }

  const foundIndex = state.routes.findIndex(leaf => nextLeaf && leaf.key === nextLeaf.key);
  const foundNextLeaf = foundIndex > -1;

  if (foundNextLeaf) {
    const foundLeaf = state.routes[foundIndex];
    // `nextLeaf` has one child, always. See `createState()`
    if (hasNextChild(nextLeaf)) {
      const nextAction: NavigationAction = {
        ...action,
        nextNavigationState: nextLeaf,
      };

      return {
        ...state,
        routes: [
          ...state.routes.slice(0, foundIndex),
          defaultReducer(foundLeaf, nextAction),
          ...state.routes.slice(foundIndex + 1, state.routes.length),
        ],
        index: foundIndex,
        ...extractCapturedState(nextState),
      };
    }

    // nextLeaf is the final leaf (nextState has no grandchild), update index and stop For stacks,
    // when a location descriptor with the same key is pushed, it's assumed POP, re-activate leaf
    // and slice off the tail
    return {
      ...state,
      routes: [
        ...state.routes.slice(0, foundIndex + 1),
      ],
      index: foundIndex,
      ...extractCapturedState(nextState),
    };
  }

  // Push a new child
  return {
    ...state,
    routes: [
      ...state.routes,
      nextLeaf,
    ],
    index: state.routes.length,
    ...extractCapturedState(nextState),
  };
}
Example #10
0
 rgb: function(r, g, b) {
   invariant(arguments.length === 3, 'rgb() takes only 3 arguments');
   return new RGBA(r, g, b);
 },
Example #11
0
 value: function getRenderedComponent() {
   invariant(this.props.withRef, 'If you want to access getRenderedComponent(), ' + 'you must specify a withRef prop to Field');
   return this.ref ? this.ref.getWrappedInstance().getRenderedComponent() : undefined;
 }
	/**
	 * @param {object} options
	 * @param {function} options.init - this fn should set up initial state and
	 *	also be used to call `bindActions`
	 * @param {object} [options.private] - object of private functions, usually
	 *	modifiers. Not every store will need this!
	 * @param {object} options.public - object of public functions, usually
	 *	accessors
	 * @param {string} options.displayName - a human readable name, used for
	 *	debugging
	 */
	constructor(options) {
		super(options);

		let publicMethods;
		let privateMethods;
		let privateMembers;
		let bindActionsWasCalled;

		const store = this;
		this.dispatchToken = null;

		// This must be below displayName for displayName uniqueness checks

		publicMethods = Object.assign(this, options.public);

		privateMethods = Object.create(publicMethods, {
			bindActions: {
				enumerable: true,
				value() {
					bindActionsWasCalled = true;

					let actions = new Map();
					let constant;
					let handler;
					let i = 0;

					invariant(
						arguments.length % 2 === 0,
						'The `bindActions` method of %s requires an even ' +
						'number of arguments',
						this
					);

					while (i * 2 < arguments.length) {
						constant = arguments[2 * i];
						handler = arguments[2 * i + 1];

						invariant(
							constant !== undefined && constant !== null,
							'An unrecognizable action type or source, `%s`, ' +
							'was passed to the `bindActions` method of `%s`',
							constant,
							this
						);

						invariant(
							handler instanceof Function,
							'An unrecognizable action handler, `%s`, was ' +
							'passed to the `bindActions` method of `%s` to ' +
							'handle `%s`',
							handler,
							this,
							constant
						);

						invariant(
							!actions.has(constant),
							`%s - The action %s has already ` +
							'been defined in this store.',
							this.toString(),
							constant.toString()
						);

						actions.set(constant, handler);

						debug.registerActionHandler(this, constant);
						i++;
					}

					const dispatchFunction = options.dispatchFunction || ObjectOrientedStore.defaultDispatchFunction;
					const boundDispatchFunction = dispatchFunction.bind(privateMembers, store, actions);

					/**
					 * Expose TestUtils only if we are not in the
					 * production environment for ease of testing.
					 *
					 */
					if (process.env.NODE_ENV !== 'production') {
						store.TestUtils = testUtils.call(
							store,
							options.init,
							boundDispatchFunction,
							publicMethods,
							privateMembers
						);
					}

					// Register the store with the Dispatcher
					store.dispatchToken = dispatcher.register(
						boundDispatchFunction,
						actions,
						store.__emitChanges.bind(store)
					);
				}
			}
		});

		privateMembers = Object.create(privateMethods);

		// Create private methods
		each(options.private || { }, (prop, method) => {
			invariant(
				method instanceof Function,
				'private member `%s` is not a function. Non-function private ' +
				'members should be declared inside of a Store\'s `init` ' +
				'function',
				prop
			);

			privateMethods[prop] = function privateMethod(...args) {
				const returnValue = method.apply(privateMembers, arguments);

				debug.logStore(this, prop, ...args);

				return returnValue;
			};
		});

		// Create public methods
		each(options.public, (prop, method) => {
			invariant(
				method instanceof Function,
				'public member `%s` is not a function',
				prop
			);

			publicMethods[prop] = function publicMethod() {
				// ensure no mutations happen on `this`
				let privateMembersCopy = {};
				if (process.env.NODE_ENV !== 'production') {
					each(privateMembers, (key, val) => {
						privateMembersCopy[key] = val;
					});
				}

				let result = method.apply(privateMembers, arguments);

				if (process.env.NODE_ENV !== 'production') {
					each(privateMembers, (key) => {
						invariant(
							privateMembersCopy[key] === privateMembers[key],
							`Public function ${options.displayName}.` +
							`${prop} mutated private members. Use a private ` +
							`method instead!`
						);
					});
				}

				return result;
			};
		});

		// Call the init method defined by the user's store.
		options.init.call(privateMembers);

		// If bindActions wasn't called, then we need to setup the
		// store appropriately by calling the method.
		if (!bindActionsWasCalled) {
			if (typeof console !== 'undefined') {
				console.warn('Warning: You are missing a `this.bindActions()`' +
				' method invocation inside your ' + this.toString() + '\'s ' +
				'init method');
			}
			privateMembers.bindActions();
		}
	}
Example #13
0
 /**
  * Calls callback method from Dispatcher
  *
  * @param {...*} arguments - arguments for callback method
  * @constructor
  */
 dispatch() {
   var payload = this.callback.apply(this, arguments);
   invariant(payload.actionType, "Payload object requires an actionType property");
   Dispatcher.dispatch(payload);
 }
Example #14
0
 _requireConfigured = () => {
   invariant(this.configured, `Call this.configure() first`)
 }
Example #15
0
/**
 * @typedef {object} request
 * @property {string} method
 * @property {string} route - string like /abc/:abc
 * @property {string} params
 * @property {object} [body]
 * @property {object} headers
 */

/**
 * @typedef {object} response
 * @property {Error} error - an error which occured during req or res
 * @property {object} body - content received from server (parsed)
 * @property {object} headers - set additional request headers
 * @property {number} status - http status code; 0 on failure
 */

/**
 * XHR wrapper for same-domain requests with Content-Type: application/json
 *
 * @param {Object} request
 * @param {Function} callback function
 * @return {Object} request object that is cancelable
 */
export default function implore(request, callback) {
	const response = {
		error: null
	};

	const {withCredentials=false, headers={}} = request;
	const xhr = new XMLHttpRequest();

	invariant(
		request,
		'implore requires a `request` argument'
	);

	invariant(
		typeof request.route === 'string',
		'implore requires parameter `route` to be a string'
	);

	invariant(
		typeof request.method === 'string',
		'implore requires parameter `method` to be a string'
	);

	invariant(
		typeof withCredentials === 'boolean',
		'implore requires parameter `withCredentials` to be a boolean'
	);

	invariant(
		typeof headers === 'object',
		'implore requires parameter `headers` to be an object'
	);

	xhr.open(request.method, getURLFromRequest(request));
	xhr.withCredentials = withCredentials;

	let contentTypeSetByUser = false;

	if (request.contentType) {
		deprecated(true, 'contentType in createRequest', 'headers');
		xhr.setRequestHeader('Content-Type', request.contentType);
		contentTypeSetByUser = true;
	}

	Object.keys(headers).forEach((header) => {
		if (header === 'Content-Type') {
			contentTypeSetByUser = true;
		}
		xhr.setRequestHeader(header, headers[header]);
	});

	if (!contentTypeSetByUser) {
		switch (request.method) {
			case 'POST':
			case 'PUT':
			case 'PATCH':
				xhr.setRequestHeader('Content-Type', 'application/json');
				break;
		}
	}

	xhr.onabort = function onabort() {
		callback({
			request,
			response: {
				fluxthisAborted: true
			}
		});
	};

	xhr.onreadystatechange = function onreadystatechange() {
		if (xhr.readyState === 4 && xhr.status !== 0) {
			response.body = xhr.responseText;
			response.status = xhr.status;
			response.type = xhr.getResponseHeader('Content-Type');

			if (/application\/json/.test(response.type)) {
				if (response.body && response.status !== 204) {
					try {
						response.body = JSON.parse(response.body);
					} catch (err) {
						response.status = xhr.status || 0;
						response.error = err;
					}
				}
			}

			callback({
				request,
				response
			});
		}
	};

	try {
		if (request.body) {
			if (typeof request.body === 'string') {
				xhr.send(request.body);
			} else {
				xhr.send(JSON.stringify(request.body));
			}
		}
		else {
			xhr.send();
		}
	}
	catch (err) {
		response.body = {};
		response.status = 0;
		response.error = err;

		callback({
			request,
			response
		});

		return null;
	}

	return new Request(xhr);
}
  /* eslint-disable consistent-return */
  function reduceRoutes(
    prevState: EnhancedNavigationRoute,
    currentRoute: RouteDef,
    index: number,
    allRoutes: Array<RouteDef>
  ): EnhancedNavigationRoute {
    let parentRoute;

    if (index > 0) {
      parentRoute = allRoutes[index - 1];
    }

    let path = currentRoute.path;
    let key = currentRoute.path;
    let type = currentRoute.routeType;
    let routeParams = getRouteParams(currentRoute, params);
    const transition = currentRoute.transition;
    const reducer = currentRoute.reducer;

    const indexRoute = getIndexRoute(currentRoute);

    if (indexRoute) {
      path = '[index]';
      key = '__index__';
      type = 'index';
      routeParams = getRouteParams(parentRoute, params);
    }

    const noPathRoute = getNoPathRoute(currentRoute);

    if (noPathRoute) {
      // Need access to previous route's children for calculating position of no-path routes Taking
      // into account no-path routes at root
      let positionInParent = 0;

      if (parentRoute && parentRoute.childRoutes) {
        positionInParent = parentRoute.childRoutes.findIndex(r => r === currentRoute);
      }
      path = `[visual]${positionInParent}`;
      key = `__visual__${positionInParent}`;
      type = currentRoute.routeType; // || 'visual'
    }

    const stateKey = location.state.stateKey;

    if (parentRoute && parentRoute.routeType === STACK_ROUTE) {
      key = `${key}_${stateKey}`;
    }

    if (key && path && type) {
      const state = {
        key,
        index: 0,
        routes: [],
        path,
        type,
        routeParams,
        params,
        location,
        transition,
        reducer,
      };

      if (prevState) {
        return {
          ...state,
          index: 0,
          routes: [prevState],
        };
      }

      return state;
    }
    invariant(false,
      'Incompatible route definition. Make sure peer dependecy requirements are met.',
    );
  }
Example #17
0
function validateDangerousTag(tag) {
  if (!hasOwnProperty.call(validatedTagCache, tag)) {
    invariant(VALID_TAG_REGEX.test(tag), 'Invalid tag: %s', tag);
    validatedTagCache[tag] = true;
  }
}
export function defaultRouteReducer(
  state: EnhancedNavigationRoute,
  action: NavigationAction,
): EnhancedNavigationRoute {
  invariant(
    state.type === ROUTE,
    '`%s` is configured with an invalid reducer.',
    state.type
  );

  const { nextNavigationState: nextState } = action;

  // `creteState()` always returns a unary tree
  const nextLeaf = nextState.routes[0];

  if (!nextLeaf) {
    // Return `nextState` to reset state, or `state` to maintain state
    return nextState;
  }

  const foundIndex = state.routes.findIndex(leaf => nextLeaf && leaf.key === nextLeaf.key);
  const foundNextLeaf = foundIndex > -1;

  if (foundNextLeaf) {
    const foundLeaf = state.routes[foundIndex];
    // `nextLeaf` has one child, always. See `createState()`
    if (hasNextChild(nextLeaf)) {
      const nextAction: NavigationAction = {
        ...action,
        nextNavigationState: nextLeaf,
      };

      return {
        ...state,
        routes: [
          ...state.routes.slice(0, foundIndex),
          defaultReducer(foundLeaf, nextAction),
          ...state.routes.slice(foundIndex + 1, state.routes.length),
        ],
        index: foundIndex,
        ...extractCapturedState(nextState),
      };
    }

    // nextLeaf is the final leaf (nextState has no grandchild), update index and stop
    return {
      ...state,
      routes: [
        ...state.routes.slice(0, foundIndex),
        {
          ...foundLeaf,
          ...extractCapturedState(nextLeaf),
        },
        ...state.routes.slice(foundIndex + 1, state.routes.length),
      ],
      index: foundIndex,
      ...extractCapturedState(nextState),
    };
  }

  // Replace existing child
  return {
    ...state,
    routes: [
      nextLeaf,
    ],
    index: 0,
    ...extractCapturedState(nextState),
  };
}
Example #19
0
  settings.authorizationGrants.forEach(function (grantType) {
    var grant = options.grant[grantType]
    var exchange = options.exchange[grantType]

    if (grantType === 'code') {
      invariant(
        typeof grant === 'function',
        'Option "grant.code" must be a function: %s',
        'https://github.com/jaredhanson/oauth2orize#register-grants'
      )

      invariant(
        typeof exchange === 'function',
        'Option "exchange.code" must be a function: %s',
        'https://github.com/jaredhanson/oauth2orize#register-exchanges'
      )

      server.grant(oauth2orize.grant.code(function (client, redirectUri, user, ares, done) {
        validateScope(scopes, ares.scope)

        return grant(client, redirectUri, user, ares, done)
      }))

      server.exchange(oauth2orize.exchange.code(exchange))

      return
    }

    if (grantType === 'token') {
      invariant(
        typeof grant === 'function',
        'Option "grant.token" must be a function: %s',
        'https://github.com/jaredhanson/oauth2orize#register-grants'
      )

      server.grant(oauth2orize.grant.token(function (client, user, ares, done) {
        validateScope(scopes, ares.scope)

        return grant(client, user, ares, done)
      }))

      return
    }

    if (grantType === 'owner') {
      invariant(
        typeof exchange === 'function',
        'Option "exchange.owner" must be a function: %s',
        'https://github.com/jaredhanson/oauth2orize#register-grants'
      )

      server.exchange(oauth2orize.exchange.password(function (client, username, password, scope, done) {
        validateScope(scopes, scope)

        return exchange(client, username, password, scope, done)
      }))

      return
    }

    if (grantType === 'credentials') {
      invariant(
        typeof exchange === 'function',
        'Option "exchange.credentials" must be a function: %s',
        'https://github.com/jaredhanson/oauth2orize#register-grants'
      )

      server.exchange(oauth2orize.exchange.clientCredentials(function (client, scope, done) {
        validateScope(scopes, scope)

        return exchange(client, scope, done)
      }))

      return
    }

    throw new TypeError('Unknown grant "' + key + '" type: ' + grantType)
  })
function insertFragmentIntoContentState(
  contentState: ContentState,
  selectionState: SelectionState,
  fragment: BlockMap
): ContentState {
  invariant(
    selectionState.isCollapsed(),
    '`insertFragment` should only be called with a collapsed selection state.'
  );

  var targetKey = selectionState.getStartKey();
  var targetOffset = selectionState.getStartOffset();

  var blockMap = contentState.getBlockMap();

  var fragmentSize = fragment.size;
  var finalKey;
  var finalOffset;

  if (fragmentSize === 1) {
    var targetBlock = blockMap.get(targetKey);
    var pastedBlock = fragment.first();
    var text = targetBlock.getText();
    var chars = targetBlock.getCharacterList();

    var newBlock = targetBlock.merge({
      text: (
        text.slice(0, targetOffset) +
        pastedBlock.getText() +
        text.slice(targetOffset)
      ),
      characterList: insertIntoList(
        chars,
        pastedBlock.getCharacterList(),
        targetOffset
      ),
    });

    blockMap = blockMap.set(targetKey, newBlock);

    finalKey = targetKey;
    finalOffset = targetOffset + pastedBlock.getText().length;

    return contentState.merge({
      blockMap: blockMap.set(targetKey, newBlock),
      selectionBefore: selectionState,
      selectionAfter: selectionState.merge({
        anchorKey: finalKey,
        anchorOffset: finalOffset,
        focusKey: finalKey,
        focusOffset: finalOffset,
        isBackward: false,
      }),
    });
  }

  var newBlockArr = [];

  contentState.getBlockMap().forEach(
    (block, blockKey) => {
      if (blockKey !== targetKey) {
        newBlockArr.push(block);
        return;
      }

      var text = block.getText();
      var chars = block.getCharacterList();

      // Modify head portion of block.
      var blockSize = text.length;
      var headText = text.slice(0, targetOffset);
      var headCharacters = chars.slice(0, targetOffset);
      var appendToHead = fragment.first();

      var modifiedHead = block.merge({
        text: headText + appendToHead.getText(),
        characterList: headCharacters.concat(appendToHead.getCharacterList()),
      });

      newBlockArr.push(modifiedHead);

      // Insert fragment blocks after the head and before the tail.
      fragment.slice(1, fragmentSize - 1).forEach(
        fragmentBlock => {
          newBlockArr.push(fragmentBlock.set('key', generateRandomKey()));
        }
      );

      // Modify tail portion of block.
      var tailText = text.slice(targetOffset, blockSize);
      var tailCharacters = chars.slice(targetOffset, blockSize);
      var prependToTail = fragment.last();
      finalKey = generateRandomKey();

      var modifiedTail = prependToTail.merge({
        key: finalKey,
        text: prependToTail.getText() + tailText,
        characterList: prependToTail
          .getCharacterList()
          .concat(tailCharacters),
      });

      newBlockArr.push(modifiedTail);
    }
  );

  finalOffset = fragment.last().getLength();

  return contentState.merge({
    blockMap: BlockMapBuilder.createFromArray(newBlockArr),
    selectionBefore: selectionState,
    selectionAfter: selectionState.merge({
      anchorKey: finalKey,
      anchorOffset: finalOffset,
      focusKey: finalKey,
      focusOffset: finalOffset,
      isBackward: false,
    }),
  });
}
Example #21
0
  render: function(nextElement, container, callback) {
    invariant(
      ReactElement.isValidElement(nextElement),
      'React.render(): Invalid component element.%s',
      (
        typeof nextElement === 'string' ?
          ' Instead of passing an element string, make sure to instantiate ' +
          'it by passing it to React.createElement.' :
        typeof nextElement === 'function' ?
          ' Instead of passing a component class, make sure to instantiate ' +
          'it by passing it to React.createElement.' :
        // Check if it quacks like an element
        nextElement != null && nextElement.props !== undefined ?
          ' This may be caused by unintentionally loading two independent ' +
          'copies of React.' :
          ''
      )
    );

    warning(
      container && container.tagName !== 'BODY',
      'render(): Rendering components directly into document.body is ' +
      'discouraged, since its children are often manipulated by third-party ' +
      'scripts and browser extensions. This may lead to subtle reconciliation ' +
      'issues. Try rendering into a container element created for your app.'
    );

    var prevComponent = instancesByReactRootID[getReactRootID(container)];

    if (prevComponent) {
      var prevElement = prevComponent._currentElement;
      if (shouldUpdateReactComponent(prevElement, nextElement)) {
        return ReactMount._updateRootComponent(
          prevComponent,
          nextElement,
          container,
          callback
        ).getPublicInstance();
      } else {
        ReactMount.unmountComponentAtNode(container);
      }
    }

    var reactRootElement = getReactRootElementInContainer(container);
    var containerHasReactMarkup =
      reactRootElement && ReactMount.isRenderedByReact(reactRootElement);

    if (__DEV__) {
      if (!containerHasReactMarkup || reactRootElement.nextSibling) {
        var rootElementSibling = reactRootElement;
        while (rootElementSibling) {
          if (ReactMount.isRenderedByReact(rootElementSibling)) {
            warning(
              false,
              'render(): Target node has markup rendered by React, but there ' +
              'are unrelated nodes as well. This is most commonly caused by ' +
              'white-space inserted around server-rendered markup.'
            );
            break;
          }

          rootElementSibling = rootElementSibling.nextSibling;
        }
      }
    }

    var shouldReuseMarkup = containerHasReactMarkup && !prevComponent;

    var component = ReactMount._renderNewRootComponent(
      nextElement,
      container,
      shouldReuseMarkup
    ).getPublicInstance();
    if (callback) {
      callback.call(component);
    }
    return component;
  },
Example #22
0
   }
   if (substitution != null) {
     if (Array.isArray(substitution)) {
       substitution.forEach(assertValidFragment);
     } else {
       assertValidFragment(substitution);
     }
   }
   return substitution;
 },
 __var(expression: mixed): mixed {
   const variable = QueryBuilder.getCallVariable(expression);
   if (variable) {
     invariant(
       false,
       'RelayQL: Invalid argument `%s` supplied via template substitution. ' +
       'Instead, use an inline variable (e.g. `comments(count: $count)`).',
       variable.callVariableName
     );
   }
   return QueryBuilder.createCallValue(expression);
 },
 __id(): string {
   return generateConcreteFragmentID();
 },
 __createFragment(
   fragment: ConcreteFragment,
   variableMapping: VariableMapping
 ): RelayFragmentReference {
   return new RelayFragmentReference(
     () => fragment,
     null,
Example #23
0
  _mountImageIntoNode: function(markup, container, shouldReuseMarkup) {
    invariant(
      container && (
        container.nodeType === ELEMENT_NODE_TYPE ||
          container.nodeType === DOC_NODE_TYPE
      ),
      'mountComponentIntoNode(...): Target container is not valid.'
    );

    if (shouldReuseMarkup) {
      var rootElement = getReactRootElementInContainer(container);
      if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) {
        return;
      } else {
        var checksum = rootElement.getAttribute(
          ReactMarkupChecksum.CHECKSUM_ATTR_NAME
        );
        rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);

        var rootMarkup = rootElement.outerHTML;
        rootElement.setAttribute(
          ReactMarkupChecksum.CHECKSUM_ATTR_NAME,
          checksum
        );

        var diffIndex = firstDifferenceIndex(markup, rootMarkup);
        var difference = ' (client) ' +
          markup.substring(diffIndex - 20, diffIndex + 20) +
          '\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20);

        invariant(
          container.nodeType !== DOC_NODE_TYPE,
          'You\'re trying to render a component to the document using ' +
          'server rendering but the checksum was invalid. This usually ' +
          'means you rendered a different component type or props on ' +
          'the client from the one on the server, or your render() ' +
          'methods are impure. React cannot handle this case due to ' +
          'cross-browser quirks by rendering at the document root. You ' +
          'should look for environment dependent code in your components ' +
          'and ensure the props are the same client and server side:\n%s',
          difference
        );

        if (__DEV__) {
          warning(
            false,
            'React attempted to reuse markup in a container but the ' +
            'checksum was invalid. This generally means that you are ' +
            'using server rendering and the markup generated on the ' +
            'server was not what the client was expecting. React injected ' +
            'new markup to compensate which works but you have lost many ' +
            'of the benefits of server rendering. Instead, figure out ' +
            'why the markup being generated is different on the client ' +
            'or server:\n%s',
            difference
          );
        }
      }
    }

    invariant(
      container.nodeType !== DOC_NODE_TYPE,
      'You\'re trying to render a component to the document but ' +
        'you didn\'t use server rendering. We can\'t do this ' +
        'without using server rendering due to cross-browser quirks. ' +
        'See React.renderToString() for server rendering.'
    );

    setInnerHTML(container, markup);
  },
Example #24
0
    };
  },

  getInitialState() {
    return {
      location: null,
      branch: null,
      params: null,
      components: null,
      isTransitioning: false
    };
  },

  _updateState(location) {
    invariant(
      Location.isLocation(location),
      'A <Router> needs a valid Location'
    );

    this.nextLocation = location;
    this.setState({ isTransitioning: true });

    this._getState(this.routes, location, (error, state) => {
      if (error || this.nextLocation !== location) {
        this._finishTransition(error);
      } else if (state == null) {
        warning(false, 'Location "%s" did not match any routes', location.pathname);
        this._finishTransition();
      } else {
        state.location = location;

        this._runTransitionHooks(state, (error) => {
Example #25
0
  /**
   * Writes a plural linked field such as `actors`. The response data is
   * expected to be an array of item objects. These fields are similar to
   * connections, but do not support range calls such as `first` or `after`.
   */
  _writePluralLink(
    field: RelayQuery.Field,
    state: WriterState,
    recordID: DataID,
    fieldData: mixed
  ): void {
    const storageKey = field.getStorageKey();
    invariant(
      Array.isArray(fieldData),
      'RelayQueryWriter: Expected array data for field `%s` on record `%s`.',
      field.getDebugName(),
      recordID
    );

    const prevLinkedIDs = this._store.getLinkedRecordIDs(recordID, storageKey);
    const nextLinkedIDs = [];
    let isUpdate = false;
    let nextIndex = 0;
    fieldData.forEach(nextRecord => {
      // validate response data
      if (nextRecord == null) {
        return;
      }
      invariant(
        typeof nextRecord === 'object' && nextRecord,
        'RelayQueryWriter: Expected elements for plural field `%s` to be ' +
        'objects.',
        storageKey
      );

      // Reuse existing generated IDs if the node does not have its own `id`.
      const prevLinkedID = prevLinkedIDs && prevLinkedIDs[nextIndex];
      const nextLinkedID = (
        nextRecord[ID] ||
        prevLinkedID ||
        generateClientID()
      );
      nextLinkedIDs.push(nextLinkedID);

      const path = RelayQueryPath.getPath(state.path, field, nextLinkedID);
      this.createRecordIfMissing(field, nextLinkedID, path, nextRecord);
      isUpdate = isUpdate || nextLinkedID !== prevLinkedID;

      this.traverse(field, {
        nodeID: null, // never propagate `nodeID` past the first linked field
        path,
        recordID: nextLinkedID,
        responseData: nextRecord,
      });
      nextIndex++;
    });

    this._writer.putLinkedRecordIDs(recordID, storageKey, nextLinkedIDs);

    // Only broadcast a list-level change if a record was changed/added/removed
    if (
      isUpdate ||
      !prevLinkedIDs ||
      prevLinkedIDs.length !== nextLinkedIDs.length
    ) {
      this.recordUpdate(recordID);
    }
  }
Example #26
0
    // Create a map of license text to manifest so that packages with exactly
    // the same license text are grouped together.
    const manifestsByLicense: Map<string, Map<string, Manifest>> = new Map();
    for (const manifest of manifests) {
      const {licenseText} = manifest;
      if (!licenseText) {
        continue;
      }

      if (!manifestsByLicense.has(licenseText)) {
        manifestsByLicense.set(licenseText, new Map());
      }

      const byLicense = manifestsByLicense.get(licenseText);
      invariant(byLicense, 'expected value');
      byLicense.set(manifest.name, manifest);
    }

    console.log(
      'THE FOLLOWING SETS FORTH ATTRIBUTION NOTICES FOR THIRD PARTY SOFTWARE THAT MAY BE CONTAINED ' +
      `IN PORTIONS OF THE ${String(manifest.name).toUpperCase().replace(/-/g, ' ')} PRODUCT.`,
    );
    console.log();

    for (const [licenseText, manifests] of manifestsByLicense) {
      console.log('-----');
      console.log();

      const names = [];
      const urls = [];
Example #27
0
 *
 * @internal
 */
const RelayFragmentPointer = {
  addFragment(
    record: Record,
    fragment: RelayQuery.Fragment
  ): void {
    let fragmentMap = record.__fragments__;
    if (fragmentMap == null) {
      fragmentMap = record.__fragments__ = {};
    }
    invariant(
      typeof fragmentMap === 'object' && fragmentMap != null,
      'RelayFragmentPointer: Expected record to contain a fragment map, got ' +
      '`%s` for record `%s`.',
      fragmentMap,
      record.__dataID__
    );
    const fragmentID = fragment.getConcreteFragmentID();
    let variableList = fragmentMap[fragmentID];
    if (variableList == null) {
      variableList = fragmentMap[fragmentID] = [];
    }
    invariant(
      Array.isArray(variableList),
      'RelayFragmentPointer: Expected record to contain a fragment/variable ' +
      'map, got `%s` for record `%s`.',
      variableList,
      record.__dataID__
    );
Example #28
0
 extractEvents: function(
     topLevelType,
     topLevelTarget,
     topLevelTargetID,
     nativeEvent) {
   var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType];
   if (!dispatchConfig) {
     return null;
   }
   var EventConstructor;
   switch(topLevelType) {
     case topLevelTypes.topInput:
     case topLevelTypes.topSubmit:
       // HTML Events
       // @see http://www.w3.org/TR/html5/index.html#events-0
       EventConstructor = SyntheticEvent;
       break;
     case topLevelTypes.topKeyDown:
     case topLevelTypes.topKeyPress:
     case topLevelTypes.topKeyUp:
       EventConstructor = SyntheticKeyboardEvent;
       break;
     case topLevelTypes.topBlur:
     case topLevelTypes.topFocus:
       EventConstructor = SyntheticFocusEvent;
       break;
     case topLevelTypes.topClick:
       // Firefox creates a click event on right mouse clicks. This removes the
       // unwanted click events.
       if (nativeEvent.button === 2) {
         return null;
       }
       /* falls through */
     case topLevelTypes.topContextMenu:
     case topLevelTypes.topDoubleClick:
     case topLevelTypes.topMouseDown:
     case topLevelTypes.topMouseMove:
     case topLevelTypes.topMouseOut:
     case topLevelTypes.topMouseOver:
     case topLevelTypes.topMouseUp:
       EventConstructor = SyntheticMouseEvent;
       break;
     case topLevelTypes.topDrag:
     case topLevelTypes.topDragEnd:
     case topLevelTypes.topDragEnter:
     case topLevelTypes.topDragExit:
     case topLevelTypes.topDragLeave:
     case topLevelTypes.topDragOver:
     case topLevelTypes.topDragStart:
     case topLevelTypes.topDrop:
       EventConstructor = SyntheticDragEvent;
       break;
     case topLevelTypes.topTouchCancel:
     case topLevelTypes.topTouchEnd:
     case topLevelTypes.topTouchMove:
     case topLevelTypes.topTouchStart:
       EventConstructor = SyntheticTouchEvent;
       break;
     case topLevelTypes.topScroll:
       EventConstructor = SyntheticUIEvent;
       break;
     case topLevelTypes.topWheel:
       EventConstructor = SyntheticWheelEvent;
       break;
     case topLevelTypes.topCopy:
     case topLevelTypes.topCut:
     case topLevelTypes.topPaste:
       EventConstructor = SyntheticClipboardEvent;
       break;
   }
   invariant(
     EventConstructor,
     'SimpleEventPlugin: Unhandled event type, `%s`.',
     topLevelType
   );
   var event = EventConstructor.getPooled(
     dispatchConfig,
     topLevelTargetID,
     nativeEvent
   );
   EventPropagators.accumulateTwoPhaseDispatches(event);
   return event;
 }
Example #29
0
 render() {
     return invariant(false, "<Route> elements are for config only and shouldn't be rendered");
 }
Example #30
0
/**
 * Given a ReactNode, create an instance that will actually be mounted.
 *
 * @param {ReactNode} node
 * @return {object} A new instance of the element's constructor.
 * @protected
 */
function instantiateReactComponent(node) {
  var instance;

  var isEmpty = node === null || node === false;
  if (isEmpty) {
    instance = ReactEmptyComponent.create(instantiateReactComponent);
  } else if (typeof node === 'object') {
    var element = node;
    invariant(
      element && (typeof element.type === 'function' ||
                  typeof element.type === 'string'),
      'Element type is invalid: expected a string (for built-in components) ' +
      'or a class/function (for composite components) but got: %s.%s',
      element.type == null ? element.type : typeof element.type,
      getDeclarationErrorAddendum(element._owner)
    );

    // Special case string values
    if (typeof element.type === 'string') {
      instance = ReactHostComponent.createInternalComponent(element);
    } else if (isInternalComponentType(element.type)) {
      // This is temporarily available for custom components that are not string
      // representations. I.e. ART. Once those are updated to use the string
      // representation, we can drop this code path.
      instance = new element.type(element);

      // We renamed this. Allow the old name for compat. :(
      if (!instance.getHostNode) {
        instance.getHostNode = instance.getNativeNode;
      }
    } else {
      instance = new ReactCompositeComponentWrapper(element);
    }
  } else if (typeof node === 'string' || typeof node === 'number') {
    instance = ReactHostComponent.createInstanceForText(node);
  } else {
    invariant(
      false,
      'Encountered invalid React node of type %s',
      typeof node
    );
  }

  if (__DEV__) {
    warning(
      typeof instance.mountComponent === 'function' &&
      typeof instance.receiveComponent === 'function' &&
      typeof instance.getHostNode === 'function' &&
      typeof instance.unmountComponent === 'function',
      'Only React Components can be mounted.'
    );
  }

  // These two fields are used by the DOM and ART diffing algorithms
  // respectively. Instead of using expandos on components, we should be
  // storing the state needed by the diffing algorithms elsewhere.
  instance._mountIndex = 0;
  instance._mountImage = null;

  if (__DEV__) {
    var debugID = isEmpty ? 0 : nextDebugID++;
    instance._debugID = debugID;

    if (debugID !== 0) {
      var displayName = getDisplayName(instance);
      ReactInstrumentation.debugTool.onSetDisplayName(debugID, displayName);
      var owner = node && node._owner;
      if (owner) {
        ReactInstrumentation.debugTool.onSetOwner(debugID, owner._debugID);
      }
    }
  }

  // Internal instances should fully constructed at this point, so they should
  // not get any new fields added to them at this point.
  if (__DEV__) {
    if (Object.preventExtensions) {
      Object.preventExtensions(instance);
    }
  }

  return instance;
}