示例#1
0
function getEntryConfig(file, fileLastMod, config) {
    var mappingsForFile = find(config.mappings, function(item) {
        return multimatch(file, item.pages).length > 0;
    }) || {};

    var properties = ['lastmod', 'priority', 'changefreq', 'hreflang'];

    var entry = defaults(
        pick(mappingsForFile, properties),
        pick(config, properties)
    );

    if (entry.lastmod === null) {
        entry.lastmod = fileLastMod || Date.now();
    }

    //turn index.html into -> /
    var relativeFile = file.replace(/(index)\.(html?){1}$/, '', 'i');
    //url location. Use slash to convert windows \\ or \ to /
    var adjustedFile = slash(relativeFile);
    entry.loc = config.siteUrl + adjustedFile;
    entry.file = adjustedFile;

    return entry;
}
示例#2
0
Entries.prototype._distillMention = function (row) {
  if (!row || !row.data) {
    return false;
  }

  let data = pick(row.data, ['url', 'name', 'published', 'summary', 'author', 'interactionType', 'interactions']);

  data.author = pick(data.author || {}, ['name', 'photo', 'url']);

  data.url = data.url || row.url;
  data.targets = row.targets || [];
  data.type = row.type || data.interactionType || 'mention';
  data.interactions = data.interactions || [];
  data.parents = row.parents;
  data.id = row.id;

  if (row.removedTargets || row.removedTargets === null) {
    data.removedTargets = row.removedTargets || [];
  }

  data = this._resolveDerivedData(data);

  delete data.interactionType;

  return data;
};
示例#3
0
async function writePackage ({author, cli, ...data}, options) {
  const pkg = pick(data, [
    'name',
    'description',
    'license',
    'keywords'
  ])

  Object.assign(pkg, {
    main: './index.js',
    bin: !cli
      ? undefined
      : {[cli]: './cli.js'},
    author: pick(author, [
      'name',
      'email',
      'url'
    ]),
    files: [
      '*.js'
    ],
    scripts: {
      test: 'standard && tape test.js'
    }
  })

  await writeFile(
    path.resolve(options.cwd, 'package.json'),
    JSON.stringify(pkg, null, 2)
  )
}
示例#4
0
    clientStore.update(state => {
      const updatedOptions = {
        ...state.shortcutOptions,
        ...pick(options, Object.keys(state.shortcutOptions)),
      };

      const withNewNames = Object.keys(renamedOptions).reduce((acc, oldName) => {
        const newName = renamedOptions[oldName];

        if (oldName in options && !(newName in options)) {
          if (process.env.NODE_ENV !== 'production') {
            // eslint-disable-next-line no-console
            console.warn(deprecationMessage(oldName, newName));
          }

          return {
            ...acc,
            [newName]: options[oldName],
          };
        }

        return acc;
      }, updatedOptions);

      return {
        shortcutOptions: withNewNames,
      };
    });
示例#5
0
  configure (options) {
    if (!(options.recurly instanceof Recurly)) throw this.error('paypal-factory-only');
    this.recurly = options.recurly;

    this.config.display = {};

    // PayPal EC flow display customization
    if (typeof options.display === 'object') {
      this.config.display = pick(options.display, DISPLAY_OPTIONS);
    }

    if (!this.config.display.locale) this.config.display.locale = DEFAULTS.display.locale;

    // Bind pricing information to display options
    if (options.pricing instanceof Pricing) {
      this.pricing = options.pricing;

      // Set initial price if available
      if (this.pricing.price) {
        this.config.display.amount = this.pricing.price.now.total;
        this.config.display.currency = this.pricing.price.currency.code;
      }

      // React to price changes
      this.pricing.on('change', price => {
        this.config.display.amount = price.now.total;
        this.config.display.currency = price.currency.code;
      });
    }
  }
function FormView(opts) {
  opts = opts || {};
  this.clean = opts.clean || this.clean || function (res) { return res; };

  assign(this, pick(opts, pickOptions));

  this.valid = false;
  this.preventDefault = opts.preventDefault === false ? false : true;
  this.autoAppend = opts.autoAppend === false ? false : true;
  opts.autoRender = opts.autoRender === false ? false : true;

  // storage for our fields
  this._fieldViews = {};
  this.subviews = this._fieldViewsArray = [];

  this.submitCallback = bind(this.submitCallback, this, this);
  this.valid = true;

  if(!this.el) this.el = document.createElement('form');

  if (this.initialize) this.initialize.apply(this, arguments);

  // add all our fields
  (opts.fields || result(this, 'fields') || []).forEach(this.addField.bind(this));
}
module.exports = (config, req, res) => {
    const settings = getSettings(config.security)
        , browser = platform.parse(req.headers['user-agent'])
        , handler = getHandler(browser)
        , directives = splitDirectives(pick(settings, policyConfig.supportedDirectives))
        , headerData = handler(browser, directives, settings);

    let policyString;

    if (settings === false) {
        return res;
    }

    checkOptions(settings);

    if (settings.setAllHeaders) {
        headerData.headers = policyConfig.allHeaders;
    }

    if (headerData.headers.length) {
        policyString = getPolicyString(browser, headerData.directives || directives);
    }

    headerData.headers.forEach((header) => {
        let headerName = header;

        if (settings.reportOnly) {
            headerName += '-Report-Only';
        }
        res.setHeader(headerName, policyString);
    });

    return res;
};
示例#8
0
    test('remote', async () => {
      const oldFile = await pouch.byRemoteIdMaybeAsync(file._id)
      await prep.moveFileAsync('remote', {
        ...pick(oldFile, ['docType', 'size', 'md5sum', 'class', 'mime', 'tags']),
        path: 'dst/file',
        updated_at: '2017-06-19T08:19:26.769Z',
        remote: {
          _id: file._id,
          _rev: pouchdbBuilders.rev()
        }
      }, oldFile)

      should(helpers.putDocs('path', '_deleted', 'trashed')).deepEqual([
        {path: path.normalize('src/file'), _deleted: true},
        {path: path.normalize('dst/file')}
      ])

      await helpers.syncAll()

      should(await helpers.local.tree()).deepEqual([
        'dst/',
        'dst/file',
        'src/'
      ])
    })
示例#9
0
  authenticate: oneFlight('authenticate', function authenticate(options) {
    this.logger.info('credentials(shim): authenticating');

    /* eslint complexity: [0] */
    options = options || {};
    if (this.isAuthenticated && !options.force) {
      this.logger.info('credentials(shim): authentication not expired, not authenticating');
      return Promise.resolve();
    }

    this.set(pick(options, 'name', 'orgId', 'password'));
    if (this.canRefresh || options.code || (this.name && this.orgId && this.password)) {
      return CredentialsBase.prototype.authenticate.apply(this, arguments);
    }

    this._isAuthenticating = true;
    switch (this.config.clientType) {
      case 'confidential':
        return this.initiateAuthorizationCodeGrant(options);
      case 'public':
        return this.initiateImplicitGrant(options);
      default:
        return Promise.reject(new Error('config.credentials.clientType must be defined'));
    }
  }),
示例#10
0
module.exports = function csp(passedOptions) {
  var options = camelize(passedOptions) || { defaultSrc: "'self'" };
  checkOptions(options);

  var directives = pick(options, config.supportedDirectives);

  return function csp(req, res, next) {
    var browser = platform.parse(req.headers["user-agent"]);
    var browserHandler = browserHandlers[browser.name] || browserHandlers.default;

    var headerData = browserHandler(browser, directives, options);

    if (options.setAllHeaders) {
      headerData.headers = config.allHeaders;
    }
    headerData.directives = headerData.directives || directives;

    var policyString;
    if (headerData.headers.length) {
      policyString = cspBuilder({ directives: headerData.directives });
    }

    headerData.headers.forEach(function(header) {
      var headerName = header;
      if (options.reportOnly) { headerName += "-Report-Only"; }
      res.setHeader(headerName, policyString);
    });

    next();
  };
};
示例#11
0
test('intent while in state createCompleted w/o error', t => {
  inst._state.setAsCreateCompleted();
  t.is(inst.setIntent(STUB).intent, STUB);
  t.deepEqual(pick(inst._state.optionsManifest(), ['intent']), {
    intent: true
  });
});
示例#12
0
test('version while in state createCompleted w/o error', t => {
  inst._state.setAsCreateCompleted();
  t.is(inst.setVersion(STUB).version, STUB);
  t.deepEqual(pick(inst._state.optionsManifest(), ['version']), {
    version: true
  });
});
示例#13
0
  getAllContent: function getAllContent(channel, query) {
    var defaultQuery = {
      contentsLimit: MAX_CONTENTS_GET
    };

    query = query ? assign(defaultQuery, pick(query, 'contentsLimit')) : defaultQuery;

    function loop(contents) {
      if (!contents.link || !contents.link.next) {
        return Promise.resolve(contents.items);
      }

      return this.spark.request({
        uri: contents.link.next
      })
        .then(function decryptContents(res) {
          contents.link = this.spark.board.parseLinkHeaders(res.headers.link);
          return this.spark.board.decryptContents(res.body);
        }.bind(this))

        .then(function getMoreContents(res) {
          contents.items = contents.items.concat(res);
          return contents;
        }.bind(this))
        .then(loop.bind(this));
    }

    return this._getPageOfContents(channel, query)
      .then(loop.bind(this));
  },
示例#14
0
test('feedback while in state createCompleted w/o error', t => {
  inst._state.setAsCreateCompleted();
  t.is(inst.setAsNotFeedback().feedback, false);
  t.deepEqual(pick(inst._state.optionsManifest(), ['feedback']), {
    feedback: true
  });
});
示例#15
0
module.exports = (entity, formatData) => {
  const { keep, languages, simplified } = formatData
  const filterAttributes = keep != null
  const filterLanguages = languages != null

  // keep only the desired attributes
  if (filterAttributes) entity = pick(entity, keep)

  // with the desired languages
  if (filterLanguages) {
    attributesWithLanguages.forEach(attr => {
      if (entity[attr]) entity[attr] = pick(entity[attr], languages)
    })
    entity.sitelinks = keepMatchingSitelinks(entity.sitelinks, languages)
  }

  // with simplified claims and text attributes if requested
  if (simplified) {
    simplify(entity, 'labels')
    simplify(entity, 'descriptions')
    simplify(entity, 'aliases')
    simplify(entity, 'claims')
    simplify(entity, 'sitelinks')
  }

  return entity
}
示例#16
0
  _extractTokenInfo: function _extractTokenInfo(query) {
    var tokenKeys = [
      'access_token',
      'expires_in',
      'token_type',
      'refresh_token',
      'refresh_token_expires_in'
    ];

    query.state = querystring.parse(base64.fromBase64url(query.state));

    this._verifySecurityToken(query.state.csrf_token);

    var token = pick(query, tokenKeys);
    token.expires_in = parseInt(token.expires_in);
    token.refresh_token_expires_in = parseInt(token.refresh_token_expires_in);
    var auth = new Authorization(token);
    this._pushAuthorization(auth);

    query = omit(query, tokenKeys);
    query.state = omit(query.state, 'csrf_token');
    if (Object.keys(query.state).length === 0) {
      delete query.state;
    }
    else {
      query.state = base64.toBase64Url(querystring.stringify(query.state));
    }

    return query;
  },
示例#17
0
test('not_handled while in state createCompleted w/o error', t => {
  inst._state.setAsCreateCompleted();
  t.is(inst.setAsNotHandled().not_handled, true);
  t.deepEqual(pick(inst._state.optionsManifest(), ['not_handled']), {
    not_handled: true
  });
});
示例#18
0
文件: mapper.js 项目: solshark/custos
 return new Promise((fulfill, reject) => {
   if (!opts) return reject(new Error('opts is required'));
   const ALLOWED_FIELDS = [
     'ip',
     'label',
     'id',
   ];
   const body = pick(opts, ALLOWED_FIELDS);
   const REQUIRED_FIELDS = [
     'id',
   ];
   REQUIRED_FIELDS.forEach((field) => {
     if (!body[field]) return reject(new Error(`opts.${field} is required`));
   });
   const url = `${this.API_ENDPOINT}/add`;
   fetch(url, {
     method: 'POST',
     headers: {
       Accept: 'application/json',
       'Content-Type': 'application/json',
       'User-Agent': `Custos-JS-Client-${this.VERSION}`,
       'x-api-key': this.API_KEY,
     },
     body: JSON.stringify(body),
   }).then((res) => fulfill(res)).catch((err) => reject(err));
 });
示例#19
0
Monitor.prototype._init = function (options) {
  options = options || {}

  defConf = conf.File(options.confFile || path.resolve(__dirname, '..', Monitor.DEF_CONF_FILE)).loadSync().valueOf()
  defConf = _.pick.call(null, defConf, Monitor.ACCEPT_KEYS)

  options = _.pick.apply(options, Monitor.ACCEPT_KEYS).valueOf()
  options = _.defaults(options, defConf)

  options.pm2 = this._resolveHome(options.pm2)
  Log(options.log)

  // Load PM2 config.
  var pm2ConfPath = path.join(options.pm2, 'conf.js')
  var fbMsg = ''
  try {
    options.pm2Conf = require(pm2ConfPath)(options.pm2)
    if (!options.pm2Conf) {
      throw new Error(404)
    }
  } catch (err) {
    fbMsg = 'Can not load PM2 config, the file "' + pm2ConfPath + '" does not exist or empty, fallback to auto-load by pm2 home. '
    console.warn(fbMsg)
    options.pm2Conf = {
      DAEMON_RPC_PORT: path.resolve(options.pm2, 'rpc.sock'),
      DAEMON_PUB_PORT: path.resolve(options.pm2, 'pub.sock'),
      PM2_LOG_FILE_PATH: path.resolve(options.pm2, 'pm2.log')
    }
  }

  Monitor.PM2_DAEMON_PROPS.forEach(function (prop) {
    var val = options.pm2Conf[prop]
    if (!val || !fs.existsSync(val)) {
      throw new Error(fbMsg + 'Unfortunately ' + (val || prop) + ' can not found, please makesure that your pm2 is running and the home path is correct.')
    }
  })

  // Bind socket.io server to context.
  if (options.sockio) {
    this.sockio = options.sockio
    delete options.sockio
  }

  // Bind to context.
  this.options = options
  Object.freeze(this.options)
}
示例#20
0
PouchDbStoreLoader.prototype._extract = function () {
  var options = _.first(arguments);

  var result = _.pick.apply(options, arguments);
  options = _.omit(options, arguments);

  return result;
};
示例#21
0
export const composer = ({ shortcuts }) => {
  return pick(
    shortcuts,
    'showLeftPanel',
    'showDownPanel',
    'goFullScreen'
  );
};
示例#22
0
 hierarchy =>
   hierarchyContainsStories(hierarchy) && (
     <Stories
       key={hierarchy.name}
       {...pick(this.props, storyProps)}
       storiesHierarchy={hierarchy}
     />
   )
DocumentObfusticateStream.prototype._transform = function (chunk, encoding, callback) {
  var itemKeys = Object.keys(chunk)
    , schema = pick(this.schema, itemKeys)

  chunk = extend({}, chunk, generateFakeData(schema))
  this.push(chunk)
  callback()
}
示例#24
0
文件: index.js 项目: ROMB/npdynamodb
  function Model(attributes){
    this.tableName = tableName;

    _.extend(this, _.pick.apply(null, [prototypeProps].concat(reservedProps)));

    this._attributes = attributes || {};

    this._builder = this.npdynamodb().table(tableName);
  }
示例#25
0
    clientStore.update((state) => {
      const newOptions = pick(options, Object.keys(state.uiOptions));
      const updatedOptions = {
        ...state.uiOptions,
        ...newOptions,
      };

      return { uiOptions: updatedOptions };
    });
示例#26
0
test('feedback while in state createCompleted w/o error', t => {
  const response = {test: true};
  inst._state.setAsCreateCompleted(response);
  t.is(inst.setAsFeedback().feedback, true);
  t.deepEqual(pick(inst._state.optionsManifest(), ['feedback']), {
    feedback: true
  });
  t.is(inst.getCreateResponse(), response);
});
示例#27
0
 toJSON: function() {
   let json = toJSON.apply(this, arguments);
   if (this.visible) {
     json = _.pick.apply(_, [json].concat(this.visible));
   }
   if (this.hidden) {
     json = _.omit.apply(_, [json].concat(this.hidden));
   }
   return json;
 }
示例#28
0
 GruntEnv.prototype.parse = function(args) {
   if (args instanceof Array) {
     this.envs = args;
   } else {
     var selectedEnvs = pick(args, function(value) {
       return value === true;
     });
     this.envs = keys(selectedEnvs);
   }
 };
示例#29
0
文件: helpers.js 项目: hon2a/reactour
export const getNodeRect = node => {
  return pick(node.getBoundingClientRect(), [
    'top',
    'right',
    'bottom',
    'left',
    'width',
    'height',
  ])
}
示例#30
0
  const updatePaginationQuery = () => {
    const { pagination } = store.getState();

    updateQueryString(pick(pagination, [
      'page',
      'perPage',
      'initialLimit',
      'hasMore',
    ]));
  };