getWebpackConfig(func, pathDist, ignoreConfigPath) {
   const project = S.getProject();
   let webpackConfig = (
     R.path(['custom', 'webpack'], func) ||
     R.path(['custom', 'webpack'], project) ||
     {
       configPath: path.join(func.name, 'webpack.config.js'),
     }
   );
   const handlerName = func.getHandler().split('.')[0];
   const handlerExt = (
     R.path(['custom', 'handlerExt'], func) ||
     R.path(['custom', 'handlerExt'], project) ||
     'js'
   );
   const handlerFileName = handlerName + '.' + handlerExt;
   if (!ignoreConfigPath && webpackConfig.configPath) {
     const projectPath = S.config.projectPath;
     const configPath = path.join(projectPath, webpackConfig.configPath);
     webpackConfig = require(configPath);
   }
   webpackConfig = R.merge({
     context: path.dirname(func.getFilePath()),
     entry: './' + handlerFileName,
     output: {
       libraryTarget: 'commonjs',
       path: pathDist,
       filename: handlerFileName,
     },
   }, webpackConfig);
   return webpackConfig;
 }
Example #2
0
 handleOrderFormUpdate = async prevProps => {
   const prevOrderForm = path(['data', 'orderForm'], prevProps)
   const orderForm = path(['data', 'orderForm'], this.props)
   if (!prevOrderForm && orderForm) {
     await this.props.updateOrderForm(orderForm)
   }
 }
 getSuggestionPath = p => {
   if (R.isEmpty(p)) {
     return R.path(p, this.curSuggestions)
   }
   const cmdChain = insertBetweenPath(p)
   this.store.markState({ cmdChain })
   return R.path(cmdChain, this.curSuggestions) || {}
 }
Example #4
0
 taxRate: function (v, obj) {
   if (R.and(
     R.path(['invoiceType', 'storeOrderType']),
   R.path(['invoiceType', 'storeOrderDirection'])
   )(obj)) {
     return notEmpty('')(v);
   }
 }
Example #5
0
function eventToFootprintAdapter({ type, payload } = {}) {
  if (eventPropertiesMapping[type]) return eventPropertiesMapping[type](payload);
  return {
    userId: R.path(['recipient', 'userId'], payload),
    listId: R.path(['recipient', 'listId'], payload),
    campaignId: R.path(['campaign', 'id'], payload)
  };
}
Example #6
0
app.post('/webhook', jsonParser, async (req, res) => {
  const prUrl = path(['pull_request', 'url'], req.body)
  const prBranchHeadSha = path(['pull_request', 'head', 'sha'], req.body)
  const prRepoAuthor = path(['repository', 'owner', 'login'], req.body)
  const prRepoName = path(['repository', 'name'], req.body)
  const prBranchName = path(['pull_request', 'head', 'ref'], req.body)

  //ej({webhook: req.body})

  ej({prRepoAuthor, prRepoName, prBranchHeadSha, prBranchName})
  //ej({prUrl})

  const prFilesMetadata = await getJsonFromHttp(prUrl + '/files')
  const jsFilesMetadata = filterJsFiles(prFilesMetadata)

  //ej({jsFilesMetadata})

  const newBranchName = `${prBranchName}-reachSuggestions-${Math.floor((Math.random() * 1000) + 1)}`
  const newBranchRef = await createBranch(prRepoAuthor, prRepoName, prBranchHeadSha, newBranchName).then(prop('ref'))

  const processedContents = await pipeP(
    pipe(
      map(
        (jsFileMetaData) => pipeP(
          prop('contents_url'),
          getJsonFromHttp,
          tap(ej),
          prop('download_url'),
          tap(ej),
          getBodyFromHttp,
          commentOutEverything,
          (newContents) => ({newContents, jsFileMetaData}) // TODO remove this weird device
        )(jsFileMetaData)
      ),
      all
    )
  )(jsFilesMetadata)

  for (let processedContent of processedContents) {
    const update = await updateFile(
      prRepoAuthor,
      prRepoName,
      processedContent.jsFileMetaData.filename,
      processedContent.jsFileMetaData.sha,
      newBranchName,
      `commenting out: ${processedContent.jsFileMetaData.filename}`,
      processedContent.newContents
    ).catch(console.log)

    console.log(`update: ${update}`)
  }

  ej({newBranchRef})

  ej({processedContents})

  res.send(s(req.body))
})
Example #7
0
 return data.reduce((arr, item) => {
   if (item.id === 'jubilee' || item.id === 'metropolitan') {
     arr.push({
         line: path(['name'], item),
         status: path(['lineStatuses', 0, 'statusSeverityDescription'], item)
       })
   }
   return arr
 }, [])
Example #8
0
 return function () {
   return R.pipeP(
     db.viewAsync,
     R.nth(0),
     R.path(['rows']),
     R.map(R.path(['value'])),
     docsObj,
     db.bulkAsync,
     compactDocs
   )('compact', 'docs')
 }
Example #9
0
export const getLocals = wrap(function *({ targetDir }, config) {
  return yield {
    title: prop('title', config),
    js: getJsFilePath(targetDir, config).then(defaultToEmptyStr(renderJS(targetDir, config))),
    css: getCssFilePath(targetDir, config).then(defaultToEmptyStr(renderCSS(config))),
    html: getHtmlFilePath(targetDir, config).then(defaultToEmptyStr(renderHTML(config))),
    cssBaseContent: getCssBaseContent(path(['css', 'base'], config)),
    stylesheets: path(['css', 'external'], config),
    scripts: path(['js', 'external'], config),
  };
});
Example #10
0
function withAuthHeaders(state, extra) {
  const token = R.path(['auth', 'settings', 'oauthToken'], state)

  return Object.assign({}, extra, !token ? {} : {
    Authorization: `Bearer ${token}`,
  })
}
Example #11
0
  onError: (resource, operation, error, dispatch) => {
    if (path(['response', 'status'], error) === 401) {
      return dispatch(clearToken())
    }

    dispatch(addError(`Error: ${operation}:${resource.name} - ${error}`))
  },
Example #12
0
function pug(bot, msg, suffix) {
  let count = 1;
  if (suffix && suffix.split(' ')[0] === 'bomb') {
    count = Number(suffix.split(' ')[1]) || 5;
    if (count > 15) count = 15;
    if (count < 0) count = 5;
  }

  const options = {
    url: `https://pugme.herokuapp.com/bomb?count=${count}`,
    headers: {
      Accept: 'application/json'
    },
    json: true
  };

  request(options)
    .then(R.path(['body', 'pugs']))
    .then(R.join('\n'))
    .then(text => bot.sendMessage(msg.channel, text))
    .catch(err => {
      sentry(err, 'images', 'pug');
      bot.sendMessage(msg.channel, `Error: ${err.message}`);
    });
}
Example #13
0
 mapStateToProps: state => ({
   backends: R.pipe(
     R.values,
     R.sortBy(R.path(['metadata', 'accessed'])),
     R.reverse
   )(state.backends.available)
 }),
export default async function pipeline(event) {
    log.info(event);
    const rawReading = event.data.element;
    const source = (
        rawReading.source ?
        rawReading.source :
        path(["measurements", "0", "source"], rawReading)
    );
    /*
     *   Workaround: some events have been incorrectly generated and thus don't
     *   have an `element` property. When processing said events, just return and
     *   move on without failing, as failures can block the kinesis stream.
     */
    if (!rawReading ||
        !rawReading.sensorId ||
        !(source === "reading") ||
        !rawReading.measurements ||
        !rawReading.measurements.find(x => x.type === "activeEnergy") &&
        !rawReading.measurements.find(x => x.type === "maxPower") &&
        !rawReading.measurements.find(x => x.type === "reactiveEnergy")
    ) {
        return null;
    }

    await insertConsumption(rawReading);
}
Example #15
0
  context('.open', function () {
    beforeEach(function () {
      sinon.stub(open, 'start').resolves()
    })

    const getCallArgs = R.path(['lastCall', 'args', 0])
    const getStartArgs = () => {
      expect(open.start).to.be.called

      return getCallArgs(open.start)
    }

    it('calls open#start, passing in options', function () {
      return cypress.open({ foo: 'foo' })
      .then(getStartArgs)
      .then((args) => {
        expect(args.foo).to.equal('foo')
      })
    })

    it('normalizes config object', () => {
      const config = {
        pageLoadTime: 10000,
        watchForFileChanges: false,
      }

      return cypress.open({ config })
      .then(getStartArgs)
      .then((args) => {
        expect(args).to.deep.eq({ config: JSON.stringify(config) })
      })
    })
  })
Example #16
0
  /**
   * Loads the given component.
   *
   * @param component:  The component Type (e.g. MyComponent)
   *                    or created component element (e.g.: <MyComponent/>).
   */
  component(component) {
    invariant(component, 'Cannot load: a component was not specified (undefined/null)');

    // Create a props object of any props set by this.props with props
    // passed down by JSX.
    const props = R.merge(
      this[PROP]('componentProps'), // Existing props from this.props()
      R.omit('children', component.props) // Don't include props.children in
                                          // props plucked from JSX
    );

    // Update the props in internal state.
    this[PROP]('componentProps', props);

    // Find the children of the passed JSX component (if any).
    const children = R.path(['props', 'children'], component);

    // Update internal state with these children.
    if (children) this[PROP]('componentChildren', children);

    // Load the component in the window.
    api.loadComponent(component);

    // Update the window state with internal state
    api.setCurrent(this[PROP].state);
    return this;
  }
Example #17
0
    client.query(`SELECT crimes from crimes_by_year where year = ${requestedYear}`, function(err, result) {
      done();

      if(err)
        return console.error('error running query', err);

      const crimes = R.pipe(
        R.path(['rows', 0, 'crimes']),
        R.sortBy(R.prop('at')),
        R.map((c) => {
          const date = new Date(c.at);
          return [Number(c.latitude), Number(c.longitude), crimeTypes[c.type], date.getMonth(), date.getDate()];
        }),
      )(result);


      const data = {
        years: R.range(2013, currentYear+1),
        crimes: crimes,
        year: requestedYear,
      };

      res.render('index.html', { data: data });
      return;
    });
function getMeasurementObject (aggregate) {
    const measurementTimes = (path(["measurementTimes"], aggregate) || "").split(",");
    return (acc, value, index) => acc.concat({
        value,
        time: measurementTimes[index]
    });
}
Example #19
0
 it(`should not lex ${reservedWord} as an identifier`, () => {
   const node = lexer(reservedWord)
   if (debug) {
     console.log(JSON.stringify(node, null, 2)) // eslint-disable-line no-console
   }
   expect(node.result).toBe('Success')
   expect(R.path(['value', 'value', 'ref'], node)).not.toBe('Identifier')
 })
Example #20
0
function sortMarbleDoms$(marbles$) {
  const doms$ = Collection.pluck(marbles$, prop('DOM'));
  const dataList$ = Collection.pluck(marbles$, prop('data'));

  return Observable.combineLatest(doms$, dataList$, zip)
    .map(sortBy(path([1, 'time'])))
    .map(map(prop(0)));
}
Example #21
0
const getAndInsertImages = response =>
  R.pipe(
    R.path(['albums', 'data']),
    filterPhotosForMenu,
    insertItemAndTypePhotos(response.id),
    // can't be called first-class, no idea why
    x => Promise.all(x))
  (response);
Example #22
0
 var getAtPath = function getAtPath(path, o) {
   // This is a temporary special case that
   // eventually will require a rewrite of `R.path`.
   if (path && path[0] === '$v') {
     return o;
   }
   return R.path(path, o);
 };
Example #23
0
const reducer = (state: Object={}, action: Object) => {
  const {status, config:{identifier}, meta} = R.path(['meta', 'middleman'], action)
  if (status === 'complete') {
    const identifierLens = R.lensProp(identifier)
    return R.over(identifierLens, R.assoc('cursor', meta.cursor), state)
  }
  return state
}
function getReadingSource (reading) {
    const source = (
        reading.source ?
        reading.source :
        path(["measurements", "0", "source"], reading)
    );
    assert(is(String, source), "Reading has no source");
    return source;
}
Example #25
0
function feedback(client, evt, suffix, lang, shard_message) {
  if (!nconf.get('FEEDBACK_CHANNEL_ID')) return Promise.resolve(T('feedback_setup', lang));
  if (!suffix) return Promise.resolve(T('feedback_usage', lang));

  let message;
  if (shard_message) {
    message = suffix;
  } else {
    message = `**(${evt.message.author.username}) [${evt.message.author.id}]\n(${R.path(['guild', 'name'], evt.message) || 'DM'}) [${R.path(['guild', 'id'], evt.message) || 'DM'}]**\n${suffix.replace(/([@#*_~`])/g, '\\$1')}`;
  }

  const channel = client.Channels.find(channel => channel.id === nconf.get('FEEDBACK_CHANNEL_ID'));
  if (channel) channel.sendMessage(message);
  if (!channel && !shard_message && nconf.get('SHARDING')) getShardsCmdResults('feedback', message);
  if (evt && evt.message) evt.message.reply(T('feedback_reply', lang));

  return Promise.resolve();
}
	test('mongodb-cache connection', ({ context }) => {
		const { uri, partition } = R.path(
			['provider', 'options'],
			context.provisioned
		);

		expect(uri).to.equal(MONGODB_ADDON_URI);
		expect(partition).to.equal(MONGODB_ADDON_DB);
	});
Example #27
0
  sendModifiedItemsToServer = async modifiedItems => {
    const { showToast, intl, updateItemsSentToServer } = this.props
    const [itemsToAdd, itemsToUpdate] = this.partitionItemsAddUpdate(modifiedItems)
    await updateItemsSentToServer()
    const pickProps = map(pick(['id', 'index', 'quantity', 'seller', 'options']))
    try {
      const updateItemsResponse = await this.updateItems(pickProps(itemsToUpdate))
      const removedItems = itemsToUpdate.filter(({ quantity }) => quantity === 0)
      if (removedItems.length) {
        this.props.push({
          event: 'removeFromCart',
          items: removedItems,
        })
      }
      const addItemsResponse = await this.addItems(pickProps(itemsToAdd))

      if (itemsToAdd.length > 0) {
        this.props.push({
          event: 'addToCart',
          items: map(this.getAddToCartEventItems, itemsToAdd),
        })
      }
      const newModifiedItems = this.getModifiedItemsOnly()
      if (newModifiedItems.length > 0) {
        // If there are new modified items in cart, recursively call this function to send requests to server
        return this.sendModifiedItemsToServer(newModifiedItems)
      }

      const newOrderForm = pathOr(
        path(['data', 'addItem'], addItemsResponse),
        ['data', 'updateItems'],
        updateItemsResponse
      )
      await this.props.updateOrderForm(newOrderForm)
    } catch (err) {
      // TODO: Toast error message into Alert
      console.error(err)
      // Rollback items and orderForm
      const orderForm = path(['data', 'orderForm'], this.props)
      showToast({ message: intl.formatMessage({ id: 'store/minicart.checkout-failure' }) })
      await this.props.updateOrderForm(orderForm)
    }
    this.setState({ updatingOrderForm: false })
  }
Example #28
0
const vf = function([obj, form]) {
  let readonly = R.path(['accountTerm', 'closed'])(obj);
  return h('.object-app', [
    h(
      classNames('header', dirty(obj) && 'dirty'),
      obj.id? `编辑凭证-${obj.number}` + (readonly? '(已锁定)': ''): '创建新凭证'
    ),
    form,
  ]);
};
Example #29
0
const validate = (val, ruleObj) => {
  if (!val) {
    return true;
  }

  const pathToFile = R.is(Object, val) ? val.path : val;
  const buffer = readChunk.sync(pathToFile, 0, 12);

  return R.path(['ext'], fileType(buffer)) === ruleObj.params[0];
};
function identifiers(x) {
  function add(name) {
    if (stack.length > 0) {
      stack[stack.length - 1].uses.push(name);
    }
  }
  switch (type(x)) {
    case 'Program':
      return R.flatten(x.body.map(identifiers));
    case 'BlockStatement':
      return R.flatten(x.body.map(identifiers));
    case 'FunctionDeclaration':
      stack.push({ name: x.id.name, uses: [], params: x.params.map(name) })
      return identifiers(x.body);
    case 'FunctionExpression':
      stack.push({ name: x.id.name, uses: [], params: x.params.map(name) })
      return identifiers(x.body);
    case 'Identifier':
      add(x.name);
      return [x.name];
    case 'ExpressionStatement':
      return identifiers(x.expression);
    case 'VariableDeclaration':
      x.declarations.forEach(function (x) {
        add(R.path(['init','name'])(x));
      });
      return x.declarations.map(R.path(['init','name']));
    case 'UpdateExpression':
      return [identifiers(x.argument)];
    case 'CallExpression':
      var calleeName = identifiers(x.callee);
      return [calleeName].concat(x.arguments.map(identifiers));
    case 'MemberExpression':
      return [identifiers(x.object)];
    case 'BinaryExpression':
      return identifiers(x.left).concat(identifiers(x.right));
    case 'VariableDeclaration':
      return x.declarations.map(R.path(['init','name']));
    default:
      console.log('do nothing for', type(x), x);
      return [];
  }
}