Skip to content
  • wincent's avatar
    Add invariant() and use it to squelch a Flow complaint in server/search.js · 85fd6821
    wincent authored
    Flow is hard-coded to grok that `invariant()` will throw an error if the
    conditional expression fails, so let's use it. Following the somewhat
    standard approach that `invariant()` gets Babel transformed so as to
    avoid the function call and evaluation of the arguments unless the
    condition is falsy.
    
    In dev, we include a full message; in prod, we just explode because the
    message is basically useless at that point (any user advanced enough to
    see the console is also capable of see the stack trace).
    
    Instead of putting an environment check in the output of the transform
    as is often done, just have our prod and dev configs toggle the
    stripping behavior. This makes the transform simpler. Instead of making
    something like:
    
      if (!condition) {
        if (/* some kind of environment check */) {
          invariant(false, ...args);
        } else {
          invariant(false);
        }
      }
    
    and then relying on the build process to constantize the env check and
    then minify the dead branch away, we directly produce either:
    
      if (!condition) {
        invariant(false, ...args);
      }
    
    or:
    
      if (!condition) {
         throw ...;
      }
    
    In playing with astexplorer.net I also noted that changing the
    CallExpression itself was not doing what I wanted (Babel will make the
    `if` "statement" safe to use in expression position by either wrapping
    it in an IIFE or turning it into a ternary). If the CallExpression is in
    a statement, as it often, but won't always, will be, then substitute the
    entire statement instead.
    
    One final observation: about that `map` over the arguments; this is
    `__DEV__` only and that whole branch gets dead-code stripped in prod,
    and O(n) of tiny n is tiny. I'm actually a little surprised that Flow is
    cool with the conditional assignment of the `invariant()` definition,
    but just going to *shrug* and move on for now...
    85fd6821