Ejemplo n.º 1
0
export function createSetters(fields: Array<any[]> | {[name: string]: any[]}, options?: Options = {}): {[name: string]: Setter} {
  if (Array.isArray(fields)) {
    fields = keyBy(fields, path => camelCase('set ' + normalize(last(path))))
  }

  return mapValues(fields, (path, name) => createSetter(path, options))
}
Ejemplo n.º 2
0
export const mergeOptions = (defaults, opt, state) => mapValues(
  merge({}, defaults, opt),
  (v, k, { params = {} }) => {
    if (isReserved(k)) return v
    return result(v, params, state)
  }
)
Ejemplo n.º 3
0
const dataToParamVectorItems = function (params, data) {
  const items = []
  forEach(params, (param, name) => {
    if (Array.isArray(data[name]) && getType(param) !== 'array') {
      const values = []
      if (data[name].length === 1) { // One value, no need to engage cross-product
        data[name] = data[name].pop()
      } else {
        forEach(data[name], value => {
          values.push({[name]: reduceXoObject(value, name)})
        })
        if (values.length) { // No values at all
          items.push({
            type: 'set',
            values
          })
        }
        delete data[name]
      }
    }
  })
  if (Object.keys(data).length) {
    items.push({
      type: 'set',
      values: [mapValues(data, reduceXoObject)]
    })
  }
  return items
}
Ejemplo n.º 4
0
Parser.prototype.clean = function() {
  this.symbols = this.symbols.filter(this.filterByProto, this);

  var byLine = groupBy(this.symbols, 'range_line');

  var singleLines = mapValues(byLine, function(symbols) {
    return sortBy(symbols, function(symbol) {
      return symbol.range_column;
    }).shift();
  });

  this.symbols = map(singleLines, function(v, k) {
    return v;
  }).filter(function(symbol) {
    var tag = this.byId.tags[symbol.id];
    var parent = this.byId.tags[symbol.parent];

    if ((/^\</).test(tag.name)) {
      return false;
    }

    return (
      tag.type ||
      (parent && parent.origin['!data'].isPlainObject) ||
      tag.origin['!data'].type
    );
  }, this);
};
Ejemplo n.º 5
0
LoggingWinston.prototype.log = function(levelName, msg, metadata, callback) {
  if (is.fn(metadata)) {
    callback = metadata;
    metadata = {};
  }

  if (this.levels_[levelName] === undefined) {
    throw new Error('Unknown log level: ' + levelName);
  }

  var levelCode = this.levels_[levelName];
  var stackdriverLevel = STACKDRIVER_LOGGING_LEVEL_CODE_TO_NAME[levelCode];

  var entryMetadata = {
    resource: this.resource_,
  };

  // Stackdriver Logs Viewer picks up the summary line from the `message`
  // property of the jsonPayload.
  // https://cloud.google.com/logging/docs/view/logs_viewer_v2#expanding.
  //
  // For error messages at severity 'error' and higher, Stackdriver
  // Error Reporting will pick up error messages if the full stack trace is
  // included in the textPayload or the message property of the jsonPayload.
  // https://cloud.google.com/error-reporting/docs/formatting-error-messages
  // We prefer to format messages as jsonPayload (by putting it as a message
  // property on an object) as that works is accepted by Error Reporting in
  // for more resource types.
  //
  // TODO(ofrobots): when resource.type is 'global' we need to additionally
  // provide serviceContext.service as part of the entry for Error Reporting to
  // automatically pick up the error.
  if (metadata && metadata.stack) {
    msg += (msg ? ' ' : '') + metadata.stack;
  }

  var data = {
    message: msg
  };

  if (is.object(metadata)) {
    data.metadata =
      this.inspectMetadata_ ? mapValues(metadata, util.inspect) : metadata;

    // If the metadata contains a httpRequest property, promote it to the entry
    // metadata. This allows Stackdriver to use request log formatting.
    // https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#HttpRequest
    // Note that the httpRequest field must properly validate as HttpRequest
    // proto message, or the log entry would be rejected by the API. We no do
    // validation here.
    if (metadata.httpRequest) {
      entryMetadata.httpRequest = metadata.httpRequest;
      delete data.metadata.httpRequest;
    }
  }

  var entry = this.log_.entry(entryMetadata, data);
  this.log_[stackdriverLevel](entry, callback);
};
Ejemplo n.º 6
0
 const NodeComponent = ({attributes, children, node}: nodeProps) => {
   return (
     <Tag
       {...attributes}
       data-slate-type={Tag}
       style={mapValues(stylesAttr, (val) => val && val(node))}
     >{children}</Tag>
   );
 };
 parse: function (data) {
     return mapValues(data, function (value, key) {
         // transform children and collections properties
         if (typeof value === 'string' && (key in this._children || key in this._collections)) {
             return {'@id': value};
         } else {
             return value;
         }
     }.bind(this));
 },
Ejemplo n.º 8
0
 set.subs = (subfields, options = {}) => {
   let suboptions = {
     ...options,
     domain: domain || ''
   }
   if (options.domain) suboptions.domain += '.' + options.domain
   if (Array.isArray(subfields)) subfields = subfields.map(subpath => [...path, ...subpath])
   else subfields = mapValues(subfields, subpath => [...path, ...subpath])
   return createSetters(subfields, suboptions)
 }
Ejemplo n.º 9
0
    constructor(...args) {
      super(...args);

      // Get the initial state from the `default*` props.
      const instanceInitialState = mapKeys(pickDefaults(this.props), fromDefaultName);
      const childProps = merge(instanceInitialState, omitDefaults(this.props));
      this.state = merge(instanceInitialState, initialize(childProps));

      // Create bound versions of the action creators.
      this.boundActionCreators = mapValues(actionCreators, fn => fn.bind(this));
    }
Ejemplo n.º 10
0
 const MarkComponent = ({ attributes, children, mark }: nodeProps) => {
   return (
     <Tag
       {...attributes}
       style={mapValues(stylesAttr, val => val && val(mark))}
       data-slate-type={Tag}
     >
       {children}
     </Tag>
   );
 };
Ejemplo n.º 11
0
 return ({ attributes, children, node }: nodeProps) => {
   return (
     <td
       style={Object.assign(mapValues(stylesAttr, val => val && val(node)), {
         minWidth: "50px"
       })}
       {...attributes}
     >
       {children}
     </td>
   );
 };
Ejemplo n.º 12
0
export default (prefix = '', resources) =>
  mapValues(resources, (endpoints) => ({
    model: endpoints[0] && endpoints[0].model
      ? exportSchema(endpoints[0].model)
      : undefined,
    endpoints: map(endpoints, (endpoint) => ({
      name: endpoint.name,
      method: endpoint.method.toUpperCase(),
      successCode: endpoint.successCode,
      path: prefix ? `${prefix}${endpoint.path}` : endpoint.path,
      instance: endpoint.instance
    }))
  })
)
Ejemplo n.º 13
0
export default function controllable(...args) {
  // Support [Python-style decorators](https://github.com/wycats/javascript-decorators)
  if (args.length === 1) return Component => controllable(Component, ...args);

  const [Component, propsOrStateManager] = args;
  let {reducers, initialize = noOpInitialize} = createStateManager(propsOrStateManager);

  // Create action creators from the reducers.
  const actionCreators = mapValues(reducers, reducer => {
    return function(...args) {
      // Calculate the new state.
      const currentProps = merge(this.state, omitDefaults(this.props), this.boundActionCreators);
      const newState = reducer(currentProps, ...args);

      // Update the state.
      this.setState(newState);

      // If there are callbacks for the changed values, invoke them.
      keys(newState).forEach(prop => {
        const newValue = newState[prop];
        const callbackName = toCallbackName(prop);
        const cb = this.props[callbackName];
        if (cb) cb(newValue);
      });
    };
  });

  return class ControllableWrapper extends React.Component {
    constructor(...args) {
      super(...args);

      // Get the initial state from the `default*` props.
      const instanceInitialState = mapKeys(pickDefaults(this.props), fromDefaultName);
      const childProps = merge(instanceInitialState, omitDefaults(this.props));
      this.state = merge(instanceInitialState, initialize(childProps));

      // Create bound versions of the action creators.
      this.boundActionCreators = mapValues(actionCreators, fn => fn.bind(this));
    }

    render() {
      const props = merge(this.state, omitDefaults(this.props), this.boundActionCreators);
      return <Component {...props} />;
    }
  };
}
Ejemplo n.º 14
0
module.exports = (fruit, basedir) => promiseAllObject(
	mapValues(
		template(fruit),
		(srcOrTransform, file) => {
			var resolved = path.resolve(basedir, file);
			return fs.exists(resolved)
				.then(exists => {
					if(exists) {
						return fs.readFile(resolved).then(orig => srcOrTransform(orig));
					} else {
						return srcOrTransform;
					}
				})
				.then(src => fs.writeFile(resolved, src));
		}
	)
);
Ejemplo n.º 15
0
export default function(Tag, blockType, stylesAttr = nodeAttrs) {
  return {
    deserialize(el, next) {
      if (blockType && el.tagName && el.tagName.toLowerCase() === Tag) {
        let data = {}

        if (el.style.textAlign) {
          data.align = el.style.textAlign;
        }

        if (el.style.lineHeight) {
          data.lineHeight = el.style.lineHeight;
        }

        if (el.style.paddingLeft) {
          data.indent = el.style.paddingLeft;
        }

        if (Object.keys(data).length > 0) {
          return {
            object: 'block',
            type: blockType,
            data,
            nodes: next(el.childNodes),
          }
        }

        return {
          object: 'block',
          type: blockType,
          nodes: next(el.childNodes),
        }
      }
    },
    serialize(obj, children) {
      if (obj.object == 'block' && obj.type === blockType) {
        return (
          <Tag style={mapValues(stylesAttr, (val) => val && val(obj))}>
            {children}
          </Tag>
        );
      }
    }
  }
}
Ejemplo n.º 16
0
export default (config, state) => {
  return {
    ...config,
    services: mapValues(config.services, (service, serviceName) => {
      if (state.services[serviceName] && state.services[serviceName]._develop) {
        return {
          ...service,
          volumes: [
            ...service.volumes || [],
            `${process.env.HOME}:${process.env.HOME}`,
          ],
        }
      }

      return service
    }),
  }
}
Ejemplo n.º 17
0
var queryize = function (original) {
	var query = {};

	// bind all mutators directly to query
	var proto = mapValues(mutators, function (fn) { return typeof fn === 'function' ? fn.bind(query) : fn; });

	// mix in the bound mutators
	Object.assign(query, proto);

	query._constructor = queryize;
	query._isQueryizeObject = true;
	query._attributes = {
		debugEnabled: false,
		database: false,
		tableName: false,
		fromSubquery: false,
		alias: false,
		dataBindings: {},
		useBoundParameters: queryize.useBoundParameters,
		where: [],
		whereBoolean: null,
		set: [],
		setKeys: {},
		columns: [ '*' ],
		joins: [],
		orderBy: false,
		groupBy: false,
		distinct: false,
		limit: false,
		asName: false,
		builder: false
	};

	if (original) {
		if (original._isQueryizeObject) {
			Object.assign(query._attributes, original.export());
		} else if (typeof original === 'object') {
			Object.assign(query._attributes, original);
		}
	}

	return query;
};
Ejemplo n.º 18
0
export default function(Tag, markType, stylesAttr = markAttrs) {
  return {
    deserialize(el, next) {
      if (markType && el.tagName && el.tagName.toLowerCase() === Tag) {
        let data = {}

        if (el.style.backgroundColor) {
          data.color = el.style.backgroundColor;
        }

        if (el.style.color) {
          data.color = el.style.color;
        }

        if (el.style.fontSize) {
          data.fontSize = el.style.fontSize;
        }

        if (el.style.letterSpacing) {
          data.letterSpacing = el.style.letterSpacing;
        }

        return {
          object: 'mark',
          type: markType,
          data,
          nodes: next(el.childNodes),
        }
      }
    },
    serialize(obj, children) {
      if (obj.object == 'mark' && obj.type === markType) {
        return (
          <Tag style={mapValues(stylesAttr, (val) => val && val(obj))}>
            {children}
          </Tag>
        );
      }
    }
  }
}
Ejemplo n.º 19
0
'use strict';

const ServiceTester = require('../service-tester');
const colorscheme = require('../../lib/colorscheme.json');
const mapValues = require('lodash.mapvalues');

const t = new ServiceTester({ id: 'website', title: 'website' });
module.exports = t;
const colorsB = mapValues(colorscheme, 'colorB');

t.create('status of http://shields.io')
  .get('/http/shields.io.json?style=_shields_test')
  .expectJSON({ name: 'website', value: 'online', colorB: colorsB.brightgreen });

t.create('status of https://shields.io')
  .get('/https/shields.io.json?style=_shields_test')
  .expectJSON({ name: 'website', value: 'online', colorB: colorsB.brightgreen });

t.create('status of nonexistent domain')
  .get('/https/shields-io.io.json?style=_shields_test')
  .expectJSON({ name: 'website', value: 'offline', colorB: colorsB.red });

t.create('status when network is off')
  .get('/http/shields.io.json?style=_shields_test')
  .networkOff()
  .expectJSON({ name: 'website', value: 'offline', colorB: colorsB.red });

t.create('custom online label, online message and online color')
  .get('-up-down-green-grey/http/online.com.json?style=_shields_test&label=homepage')
  .intercept(nock => nock('http://online.com')
    .head('/')
Ejemplo n.º 20
0
function Demo (material, opts) {
  if (!(this instanceof Demo)) return new Demo(material, opts)
  if (!material) throw Error('Must specify a material')
  if (!opts) opts = {}
  if (!opts.initial) opts.initial = mapvalues(material.styles, 'default')
  if (!opts.root) opts.root = document.body
  if (!opts.background) opts.background = [0.05, 0.05, 0.05]

  if (!opts.complex) {
    opts.complex = bunny
    opts.complex.positions = opts.complex.positions.map(function (p) {
      return [p[0], p[1] - 4, p[2]]
    })
  }

  if (!opts.canvas) {
    opts.canvas = document.createElement('canvas')
    opts.root.appendChild(opts.canvas)
  }

  window.addEventListener('resize', fit(opts.canvas), false)

  var gl = Context(opts.canvas, tick)
  var scene = Scene(gl, {background: opts.background})

  var shapes = [
    {
      id: 'shape',
      complex: opts.complex,
      flatten: opts.flatten,
      position: [0, 0, 0],
      material: 'example',
      style: opts.initial
    }
  ]

  var lights = [
    {
      position: [10, 10, 10, 1],
      style: {color: [1, 1, 1], intensity: 10.0, ambient: 1.0, radius: 30}
    }
  ]

  scene.shapes(shapes)
  scene.lights(lights)
  scene.materials({example: material})
  scene.init()

  var camera = orbit(opts.canvas)
  camera.lookAt([0, 0, 20], [0, 0, 0], [0, 0, 1])

  var t = 0

  function tick () {
    scene.draw(camera)
    scene.select('#shape').rotation(t, [0, 1, 0])
    t += 0.0075
  }

  var inputs = []
  foreach(material.styles, function (value, key) {
    switch (value.type) {
      case 'vec3':
        inputs.push({type: 'color', label: key, format: 'array', initial: opts.initial[key]})
        break
      case 'float':
        inputs.push({type: 'range', label: key, min: value.min, max: value.max, initial: opts.initial[key]})
        break
      case 'bool':
        inputs.push({type: 'checkbox', label: key, initial: opts.initial[key]})
        break
    }
  })

  var link = '<a href="https://npmjs.org/gl-lambert-material">gl-material-' + material.name + '</a>'
  var panel = control(inputs,
    {position: 'top-right', theme: 'dark', width: 300, title: link}
  )

  panel.on('input', function (data) {
    var style = {}
    foreach(data, function (value, key) {
      style[key] = value
    })
    scene.select('#shape').style(style)
  })
}
Ejemplo n.º 21
0
function eachResource(resource) {
  if (!resource.view) return

  var clientViewPath = __dirname + '/../client/plugins/' + resource.name + '/'
    , templatePath = __dirname + '/templates/view/'
    , checksumPath = __dirname + '/../client/plugins/.' + resource.name + '.md5'
    , oldChecksum, newChecksum;

  var voidElements = ['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr'];

  var attributes = toArray(mapValues(resource.model.attributes, function(value, key) {
    var inputElementAttributes = value.inputElementAttributes || {}
    if (!inputElementAttributes.type)
      inputElementAttributes.type = 'text'
    return {
      id: uuid(),
      lowercase: key.toLowerCase(),
      capitalized: caps(key),
      type: value.type,
      remove: value.remove || false,
      model: value.model ? {
        title: find(resources, { name: value.model }).view.titleField,
        name: value.model,
        capitalized: caps(value.model)
      } : false,
      inputElement: value.inputElement || 'input',
      inputIsNotVoidElement: !contains(voidElements, value.inputElement || 'input'),
      inputElementAttributes: inputElementAttributes
    }
  }));

  var viewConfig = {
    name: resource.name,
    nameCapitalized: caps(resource.name),
    nameAllCaps: resource.name.toUpperCase(),
    titleField: resource.view.titleField,
    teaserFields: returnAttributes(resource.view.teaserFields),
    detailFields: returnAttributes(resource.view.detailFields),
    attributes: attributes
  };

  function returnAttributes(fields) {
    var toReturn = [];
    for (var x in fields)
      toReturn.push(find(attributes, { lowercase: fields[x] }));
    return toReturn;
  }

  async.waterfall([

    // Read checksum from existing view plugin
    function(cb) {
      fs.readFile(checksumPath, { encoding: 'utf8' }, function (err, checksum) {
        return cb(null, checksum);
      })
    },

    // Assign to oldChecksum and read files to create newChecksum
    function(md5, cb) {
      oldChecksum = md5 || null;
      if (isNull(oldChecksum)) return cb(null, null)
      dirsum.digest(clientViewPath, 'md5', cb);
    },

    // Assign newChecksum and compare, if the same delete plugin folder
    function(hashes, cb) {
      if (isNull(oldChecksum)) return cb(null)
      newChecksum = hashes.hash;
      if (oldChecksum !== newChecksum)
        return cb(new Error('Checksum mismatch.'))
      deleteFolder(clientViewPath);
      cb(null);
    },

    // Check if plugin folder exists
    function(cb) {
      fs.lstat(clientViewPath, function(err, folderStats) {
        if (err) return cb(null, false)
        cb(null, folderStats.isDirectory());
      })
    },

    // If folder doesn't exists create it
    function(exists, cb) {
      if (exists) return cb(null)
      fs.mkdir(clientViewPath, cb)
    },

    // List files in template directory
    function(cb) {
      fs.readdir(templatePath, cb);
    },

    // Write template files
    function(files, cb) {
      async.each(files, function(file, cb) {
        fs.readFile(templatePath + file, { encoding: 'utf8' }, function(err, template) {
          if (err) return cb(err);
          hbTemplate = Handlebars.compile(template);
          fs.writeFile(clientViewPath + file.replace('.hbs', ''), hbTemplate(viewConfig), cb);
        })
      }, cb);
    },

    // Get new checksum
    function(cb) {
      dirsum.digest(clientViewPath, 'md5', cb);
    },

    // Write new checksum
    function(hashes, cb) {
      fs.writeFile(checksumPath, hashes.hash, cb);
    }
  ], function(err){
    if (err) console.error(err);
  })

}
Ejemplo n.º 22
0
}

//    __                 _                 
//   /__\ __ _ _ __   __| | ___  _ __ ___  
//  / \/// _` | '_ \ / _` |/ _ \| '_ ` _ \ 
// / _  \ (_| | | | | (_| | (_) | | | | | |
// \/ \_/\__,_|_| |_|\__,_|\___/|_| |_| |_|
//

// map to random data generator (Chance)
hazy.random = mapValues(hazy.meta.random.types, (value, key) => {
  const hazyRandObj = {}
  
  forEach(value, (v) => {
    hazyRandObj[v] = (conf) => new Chance()[v](conf)
  })
  
  return hazyRandObj
})

//    ___       _ _     _ 
//   / __\_   _(_) | __| |
//  /__\// | | | | |/ _` |
// / \/  \ |_| | | | (_| |
// \_____/\__,_|_|_|\__,_|
//

// creates a clone of the current hazy object (shallow, new memory references)
hazy.fork = () => Object.assign({}, hazy)
Ejemplo n.º 23
0
		const reducer = (state, action) => {
			let newState = rootReducer(state, action);

			// update cached ownState of root store
			rootState = newState;

			// FIXME: this reducer will also be responsible for handling queries
			// Specifically, it should update the relevant viewedStateSpec

			// FIXME: update state *before* calling root reducer
			if (action.type === MOUNT) {
				// add the initial own state of the mounted store to the root store's
				// state
				newState = immutable.set(
					newState,
					action.payload.path,
					action.payload.initialState
				);

				// prime the cached state for the mounted store
				updateCachedState(
					action.payload.path,
					_get(newState, action.payload.path)
				);

				// bypass mounted reducers for this action
				return newState;
			} else if (action.type === UNMOUNT) {
				// remove the unmounted store's own state from the root store's state
				newState = immutable.del(newState, action.payload.path);

				delete mounts[action.payload.path];
			} else if (action.type === QUERY_RESULT) {
				let mount = mounts[action.payload.path];
				let queriedStateSpec = _mapValues(
					action.payload.result,
					result => () => _get(rootState, result)
				);

				mount.viewedStateSpec =
					_assign({}, mount.viewedStateSpec, queriedStateSpec);
			}

			// FIXME: calculate this array at mount/unmount time
			// iterate over mounted reducers, breadth-first
			let paths = [];
			for (const path in mounts) {
				paths.push(path.split('.'));
			}
			paths = paths.sort(
				(pathA, pathB) => {
					return pathA.length - pathB.length;
				})
				.map(path => path.join('.'));

			function updateMountCache(path) {
				const mount = mounts[path];

				const ownState = _get(newState, path);
				const viewedState = getViewedState(path);

				if (ownState !== mount.cache.ownState ||
					viewedState !== mount.cache.viewedState
				) {
					// either the mount's own state or its viewed state have changed,
					// so recalculate its merged state
					updateCachedState(path, ownState);
				}
			}

			paths.forEach(path => {
				const mount = mounts[path];

				if (!mount.reducer) {
					// if `mount` has been called for a path, but the corresponding
					// mounted store creator *not* called, then no reducer will be
					// registered, so skip that path
					return;
				}

				updateMountCache(path);

				const newMergedState =
					mount.reducer.call(null, mount.cache.mergedState, action);

				if (newMergedState !== mount.cache.mergedState) {
					// FIXME: check that viewed state is not modified
					// FIXME: test that asserts that removed viewedState is reapplied
					mount.cache.mergedState =
						_merge(newMergedState, mount.cache.viewedState);
					mount.cache.ownState =
						_omit(newMergedState, Object.keys(mount.viewedStateSpec));
					newState = immutable.set(newState, path, mount.cache.ownState);
				}
			});

			// update cached state for all mounts
			paths.forEach(updateMountCache);

			return newState;
		};
Ejemplo n.º 24
0
export const mergeOptions = (defaults, opt) => {
  return mapValues(merge({}, opt, defaults), (v, k, { params }) => {
    if (isReserved(k)) return v
    return result(v, params)
  })
}
Ejemplo n.º 25
0
const getErrorFields = (err) => {
  if (!err.errors) return
  return mapValues(err.errors, getError)
}
Ejemplo n.º 26
0
      }
      return true;
    })
    .argv,

  glob = argv._[0] || process.cwd(),

  maxDepth = argv.maxDepth;

if (isNumber(maxDepth)) {
  argv.maxDepth = Math.floor(maxDepth);
}

argv = mapValues(argv, function (value) {
  if (isString(value)) {
    return value.replace(/\\/g, '');
  }
  return value;
})

markdownIndex(glob, argv)
  .then(function (data) {
    var inject = argv.inject,
      output = argv.output;

    if (inject) {
      return markdownIndex.inject(inject, data)
        .then(function () {
          console.log('Injected TOC into %s', inject);
        });
    }
Ejemplo n.º 27
0
function parseBundle (bundleContent) {
  const ast = acorn.parse(bundleContent, {
    sourceType: 'script',
    // I believe in a bright future of ECMAScript!
    // Actually, it's set to `2050` to support the latest ECMAScript version that currently exists.
    // Seems like `acorn` supports such weird option value.
    ecmaVersion: 2050
  })

  const walkState = {
    locations: null
  }

  walk.recursive(
    ast,
    walkState,
    {
      CallExpression (node, state, c) {
        if (state.sizes) return

        const args = node.arguments

        // Additional bundle without webpack loader.
        // Modules are stored in second argument, after chunk ids:
        // webpackJsonp([<chunks>], <modules>, ...)
        // As function name may be changed with `output.jsonpFunction` option we can't rely on it's default name.
        if (
          node.callee.type === 'Identifier' &&
          args.length >= 2 &&
          isArgumentContainsChunkIds(args[0]) &&
          isArgumentContainsModulesList(args[1])
        ) {
          state.locations = getModulesLocationFromFunctionArgument(args[1])
          return
        }

        // Additional bundle without webpack loader, with module IDs optimized.
        // Modules are stored in second arguments Array(n).concat() call
        // webpackJsonp([<chunks>], Array([minimum ID]).concat([<module>, <module>, ...]))
        // As function name may be changed with `output.jsonpFunction` option we can't rely on it's default name.
        if (
          node.callee.type === 'Identifier' &&
          (args.length === 2 || args.length === 3) &&
          isArgumentContainsChunkIds(args[0]) &&
          isArgumentArrayConcatContainingChunks(args[1])
        ) {
          state.locations = getModulesLocationFromArrayConcat(args[1])
          return
        }

        // Main bundle with webpack loader
        // Modules are stored in first argument:
        // (function (...) {...})(<modules>)
        if (
          node.callee.type === 'FunctionExpression' &&
          !node.callee.id &&
          args.length === 1 &&
          isArgumentContainsModulesList(args[0])
        ) {
          state.locations = getModulesLocationFromFunctionArgument(args[0])
          return
        }

        // Additional bundles with webpack 4 are loaded with:
        // (window.webpackJsonp=window.webpackJsonp||[]).push([[chunkId], [<module>, <module>], [[optional_entries]]]);
        if (
          isWindowPropertyPushExpression(node) &&
          args.length === 1 &&
          isArgumentContainingChunkIdsAndModulesList(args[0])
        ) {
          state.locations = getModulesLocationFromFunctionArgument(args[0].elements[1])
          return
        }

        // Walking into arguments because some of plugins (e.g. `DedupePlugin`) or some Webpack
        // features (e.g. `umd` library output) can wrap modules list into additional IIFE.
        args.forEach(arg => c(arg, state))
      }
    }
  )

  if (!walkState.locations) {
    return null
  }

  return {
    src: bundleContent,
    modules: mapValues(walkState.locations,
      loc => bundleContent.slice(loc.start, loc.end)
    )
  }
}
Ejemplo n.º 28
0
'use strict'

const chalk = require('chalk')
const mapValues = require('lodash.mapvalues')

const colorscheme = require('../lib/colorscheme.json')
const colorsMap = mapValues(colorscheme, 'colorB')
const { floorCount } = require('./color-formatters')
const { loadServiceClasses } = require('../services')

const serviceClasses = loadServiceClasses()
const legacyServices = serviceClasses
  .map(cls => (typeof cls.registerLegacyRouteHandler === 'function' ? 1 : 0))
  .reduce((a, b) => a + b)
const newServices = serviceClasses.length - legacyServices
const percentDone = ((newServices / serviceClasses.length) * 100).toFixed(2)
const color = floorCount(percentDone, 10, 50, 100)

console.log(`Found ${serviceClasses.length} services:`)
console.log(`- ${legacyServices} legacy services`)
console.log(`- ${newServices} new services`)
console.log(chalk.hex(colorsMap[color])(`${percentDone}% done`))
Ejemplo n.º 29
0
const makeMixinsConfig = colors => ({
  mixins: {
    ...mapValues(selectors, selector => selector(colors)),
  },
})
Ejemplo n.º 30
0
import {createAction} from 'redux-actions';
import mapValues from 'lodash.mapvalues';
import {Activity} from '../constants/ActionTypes';
import * as apiActions from './api';

const actions = {
  [Activity.getHistory]: () => apiActions.get(`/history?page=1&pageSize=15&sortKey=date&sortDir=desc`),
  [Activity.getQueue]: () => apiActions.get(`/queue?sort_by=timeleft&order=asc`),
};

module.exports = mapValues(actions, (action, type) => createAction(type, action));