<commit_before>/*
 * Copyright (c) 2016 Untu, Inc.
 * This code is licensed under Eclipse Public License - v 1.0.
 * The full license text can be found in LICENSE.txt file and
 * on the Eclipse official site (https://www.eclipse.org/legal/epl-v10.html).
 */

'use strict';

var actors = require('../index');
var expect = require('chai').expect;
var P = require('bluebird');

var system;

describe('Resource injection', function() {
  afterEach(P.coroutine(function*() {
    if (system) {
      yield system.destroy();
    }

    system = null;
  }));

  it('should inject resource into an in-memory actor', P.coroutine(function*() {
    /**
     * Test resource.
     */
    class MessageResource {
      static getName() {
        return 'message-text';
      }

      getResource() {
        return 'Hi there!';
      }
    }

    /**
     * Test actor, that uses test resource.
     */
    class MyActor {
      static inject() {
        return ['message-text'];
      }

      constructor(message) {
        this.message = message;
      }

      hello() {
        return this.message;
      }
    }

    system = actors({
      test: true,
      resources: [MessageResource]
    });

    var actor = yield system.rootActor().then(rootActor => rootActor.createChild(MyActor));

    var response = yield actor.sendAndReceive('hello');

    expect(response).to.be.equal('Hi there!');
  }));

  it('should inject resource into a forked actor', P.coroutine(function*() {
    /**
     * Test resource.
     */
    class MessageResource {
      static getName() {
        return 'message-text';
      }

      getResource() {
        return 'Hi there!';
      }
    }

    /**
     * Test actor, that uses test resource.
     */
    class MyActor {
      static inject() {
        return ['message-text'];
      }

      constructor(message) {
        this.message = message;
      }

      hello() {
        return this.message;
      }
    }

    system = actors({
      test: true,
      resources: [MessageResource]
    });

    var actor = yield system.rootActor().then(rootActor => rootActor.createChild(MyActor, { mode: 'forked' }));

    var response = yield actor.sendAndReceive('hello');

    expect(response).to.be.equal('Hi there!');
  }));

  it('should run resource lifecycle hooks', P.coroutine(function*() {
    var destroyed = false;

    /**
     * Test resource.
     */
    class MessageResource {
      static getName() {
        return 'message-text';
      }

      initialize() {
        this.text = 'Hi there!';
      }

      destroy() {
        destroyed = true;
      }

      getResource() {
        return this.text;
      }
    }

    /**
     * Test actor, that uses test resource.
     */
    class MyActor {
      static inject() {
        return ['message-text'];
      }

      constructor(message) {
        this.message = message;
      }

      hello() {
        return this.message;
      }
    }

    var system = actors({
      test: true,
      resources: [MessageResource]
    });

    var actor = yield system.rootActor().then(rootActor => rootActor.createChild(MyActor));

    var response = yield actor.sendAndReceive('hello');

    expect(response).to.be.equal('Hi there!');

    yield system.destroy();

    expect(destroyed).to.be.equal(true);
  }));

  it('should not initialize an unused resource', function() {
    throw new Error('TODO');
  });

  it('should support module-defined resources', function() {
    throw new Error('TODO');
  });

  it('should support TypeScript module-defined resources', function() {
    throw new Error('TODO');
  });
});<commit_msg>Working test for unused resources.<commit_after>/*
 * Copyright (c) 2016 Untu, Inc.
 * This code is licensed under Eclipse Public License - v 1.0.
 * The full license text can be found in LICENSE.txt file and
 * on the Eclipse official site (https://www.eclipse.org/legal/epl-v10.html).
 */

'use strict';

var actors = require('../index');
var expect = require('chai').expect;
var P = require('bluebird');

var system;

describe('Resource injection', function() {
  afterEach(P.coroutine(function*() {
    if (system) {
      yield system.destroy();
    }

    system = null;
  }));

  it('should inject resource into an in-memory actor', P.coroutine(function*() {
    /**
     * Test resource.
     */
    class MessageResource {
      static getName() {
        return 'message-text';
      }

      getResource() {
        return 'Hi there!';
      }
    }

    /**
     * Test actor, that uses test resource.
     */
    class MyActor {
      static inject() {
        return ['message-text'];
      }

      constructor(message) {
        this.message = message;
      }

      hello() {
        return this.message;
      }
    }

    system = actors({
      test: true,
      resources: [MessageResource]
    });

    var actor = yield system.rootActor().then(rootActor => rootActor.createChild(MyActor));

    var response = yield actor.sendAndReceive('hello');

    expect(response).to.be.equal('Hi there!');
  }));

  it('should inject resource into a forked actor', P.coroutine(function*() {
    /**
     * Test resource.
     */
    class MessageResource {
      static getName() {
        return 'message-text';
      }

      getResource() {
        return 'Hi there!';
      }
    }

    /**
     * Test actor, that uses test resource.
     */
    class MyActor {
      static inject() {
        return ['message-text'];
      }

      constructor(message) {
        this.message = message;
      }

      hello() {
        return this.message;
      }
    }

    system = actors({
      test: true,
      resources: [MessageResource]
    });

    var actor = yield system.rootActor().then(rootActor => rootActor.createChild(MyActor, { mode: 'forked' }));

    var response = yield actor.sendAndReceive('hello');

    expect(response).to.be.equal('Hi there!');
  }));

  it('should run resource lifecycle hooks for used resources', P.coroutine(function*() {
    var messageResourceInitialized = false;
    var messageResourceDestroyed = false;
    var unusedResourceInitialized = false;
    var unusedResourceDestroyed = false;

    /**
     * Test resource.
     */
    class MessageResource {
      static getName() {
        return 'message-text';
      }

      initialize() {
        this.text = 'Hi there!';
        messageResourceInitialized = true;
      }

      destroy() {
        messageResourceDestroyed = true;
      }

      getResource() {
        return this.text;
      }
    }

    /**
     * Test unused resource.
     */
    class UnusedResource {
      static getName() {
        return 'unused';
      }

      initialize() {
        unusedResourceInitialized = true;
      }

      destroy() {
        unusedResourceDestroyed = true;
      }
    }

    /**
     * Test actor, that uses test resource.
     */
    class MyActor {
      static inject() {
        return ['message-text'];
      }

      constructor(message) {
        this.message = message;
      }

      hello() {
        return this.message;
      }
    }

    var system = actors({
      test: true,
      resources: [MessageResource, UnusedResource]
    });

    var actor = yield system.rootActor().then(rootActor => rootActor.createChild(MyActor));

    var response = yield actor.sendAndReceive('hello');

    expect(response).to.be.equal('Hi there!');

    yield system.destroy();

    expect(messageResourceInitialized).to.be.equal(true);
    expect(messageResourceDestroyed).to.be.equal(true);
    expect(unusedResourceInitialized).to.be.equal(false);
    expect(unusedResourceDestroyed).to.be.equal(false);
  }));

  it('should support module-defined resources', function() {
    throw new Error('TODO');
  });

  it('should support TypeScript module-defined resources', function() {
    throw new Error('TODO');
  });
});<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { translate } from 'react-i18next'
import Dropzone from 'react-dropzone'
import Ipfs from 'ipfs-api'
import { IPFS_HOST, IPFS_PORT } from '../../../../config/config'
import styles from './style.css'

const ipfs = new Ipfs(IPFS_HOST, IPFS_PORT)

class Upload extends Component {
  state = { doc: false }

  onDrop(acceptedFiles) {
    const reader = new window.FileReader()
    reader.onload = () => {
      let data = reader.result
      data = new Buffer(data.substr(data.indexOf(',') + 1), 'base64')
      ipfs.add(data, (err, res) => {
        if (err || !res) {
          console.error(err)
          return false;
        }
        // console.log(res);
        const url = 'http://ipfs.io/ipfs/' + res[0].hash;
        this.setState({ doc: url })
        this.props.onUpload(url)
        return true;
      })
    }
    reader.readAsDataURL(acceptedFiles[0])
  }
  render() {
    return (

        <Dropzone className={'panel-body ' + styles.dropzone} activeClassName={styles.dropzoneActive} multiple={false} onDrop={files => this.onDrop(files)}>

{this.props.t('dropzoneText')}

        </Dropzone>

      {this.state.doc !== false ?

{this.state.doc}

 : null}

)
  }
}

export default translate(['docs'])(Upload)
<commit_msg>change ipfs protocol http<commit_after>import React, { Component } from 'react'
import { translate } from 'react-i18next'
import Dropzone from 'react-dropzone'
import Ipfs from 'ipfs-api'
import { IPFS_HOST, IPFS_PORT } from '../../../../config/config'
import styles from './style.css'

const ipfs = new Ipfs(IPFS_HOST, IPFS_PORT, { protocol: 'http' })

class Upload extends Component {
  state = { doc: false }

  onDrop(acceptedFiles) {
    const reader = new window.FileReader()
    reader.onload = () => {
      let data = reader.result
      data = new Buffer(data.substr(data.indexOf(',') + 1), 'base64')
      ipfs.add(data, (err, res) => {
        if (err || !res) {
          console.error(err)
          return false;
        }
        // console.log(res);
        const url = 'http://ipfs.io/ipfs/' + res[0].hash;
        this.setState({ doc: url })
        this.props.onUpload(url)
        return true;
      })
    }
    reader.readAsDataURL(acceptedFiles[0])
  }
  render() {
    return (

        <Dropzone className={'panel-body ' + styles.dropzone} activeClassName={styles.dropzoneActive} multiple={false} onDrop={files => this.onDrop(files)}>

{this.props.t('dropzoneText')}

        </Dropzone>

      {this.state.doc !== false ?

{this.state.doc}

 : null}

)
  }
}

export default translate(['docs'])(Upload)
<|endoftext|>


<commit_before>/*global define*/

define(['jquery', 'underscore', 'backbone', 'templates', 'helpers/graph-utils', 'models/application-model', 'marionette'], function($, _, Backbone, JST, gutils, models) {
    'use strict';

    var GraphwallView = Backbone.Marionette.ItemView.extend({
        template: JST['app/scripts/templates/graphwall-view.ejs'],
        className: 'graph-mode span12',
        ui: {
            'title': '.title',
            'buttons': '.btn-graph'
        },
        events: {
            'click .btn-graph .btn': 'clickHandler'
        },
        clickHandler: function(evt) {
            var $target = $(evt.target);
            var id = $target.attr('data-id');
            var route = 'graph/' + this.hostname + '/' + id;
            if (id === 'overview') {
                route = 'graph/' + this.hostname;
            }
            console.log(route);
            this.AppRouter.navigate(route, {
                trigger: true
            });
        },
        graphs: [{
            metrics: ['byte_avail', 'byte_free', 'byte_used'],
            fn: 'makeDiskSpaceBytesGraphUrl',
            util: 'makeDiskSpaceTargets'
        }, {
            metrics: ['inodes_avail', 'inodes_free', 'inodes_used'],
            fn: 'makeDiskSpaceInodesGraphUrl',
            util: 'makeDiskSpaceTargets'
        }, {
            metrics: ['system', 'user', 'idle'],
            fn: 'makeCPUGraphUrl',
            util: 'makeCPUTargets'
        }, {
            metrics: ['system', 'user', 'nice', 'idle', 'iowait', 'irq', 'softirq', 'steal'],
            fn: 'makeCPUDetailGraphUrl',
            util: 'makeCPUDetailedTargets'
        }, {
            metrics: ['op_r_latency', 'op_w_latency', 'op_rw_latency'],
            fn: 'makeOpsLatencyGraphUrl',
            util: 'makeOpLatencyTargets'
        }, {
            metrics: ['journal_ops', 'journal_wr'],
            fn: 'makeJournalOpsGraphUrl',
            util: 'makeFilestoreTargets'
        }, {
            metrics: ['01', '05', '15'],
            fn: 'makeLoadAvgGraphUrl',
            util: 'makeLoadAvgTargets'
        }, {
            metrics: ['Active', 'Buffers', 'Cached', 'MemFree'],
            fn: 'makeMemoryGraphUrl',
            util: 'makeMemoryTargets'
        }, {
            metrics: ['read_byte_per_second', 'write_byte_per_second'],
            fn: 'makeHostDeviceRWBytesGraphUrl',
            util: 'makeIOStatIOPSTargets'
        }, {
            metrics: ['read_await', 'write_await'],
            fn: 'makeHostDeviceRWAwaitGraphUrl',
            util: 'makeIOStatIOPSTargets'
        }, {
            metrics: ['iops'],
            fn: 'makeHostDeviceIOPSGraphUrl',
            util: 'makeIOStatIOPSTargets'
        }],
        makeGraphFunctions: function(options) {
            var targets = gutils.makeTargets(gutils[options.util](options.metrics));
            this[options.fn] = gutils.makeGraphURL('png', this.baseUrl, this.heightWidth, targets);
        },
        initialize: function() {
            this.App = Backbone.Marionette.getOption(this, 'App');
            this.AppRouter = Backbone.Marionette.getOption(this, 'AppRouter');
            this.graphiteHost = Backbone.Marionette.getOption(this, 'graphiteHost');
            this.baseUrl = gutils.makeBaseUrl(this.graphiteHost);
            this.heightWidth = gutils.makeHeightWidthParams(442, 266);

            _.bindAll(this, 'makeGraphFunctions');
            _.each(this.graphs, this.makeGraphFunctions);

            this.cpuTargetModels = new models.GraphiteCPUModel(undefined, {
                graphiteHost: this.graphiteHost
            });
            this.ioTargetModels = new models.GraphiteIOModel(undefined, {
                graphiteHost: this.graphiteHost
            });
        },
        makeCPUDetail: function(hostname) {
            return this.makePerHostGraphs(hostname, this.makeCPUDetailGraphUrl, this.cpuTargetModels);
        },
        makeHostDeviceIOPS: function(hostname) {
            return this.makePerHostGraphs(hostname, this.makeHostDeviceIOPSGraphUrl, this.ioTargetModels);
        },
        makeHostDeviceRWBytes: function(hostname) {
            return this.makePerHostGraphs(hostname, this.makeHostDeviceRWBytesGraphUrl, this.ioTargetModels);
        },
        makeHostDeviceRWAwait: function(hostname) {
            return this.makePerHostGraphs(hostname, this.makeHostDeviceRWAwaitGraphUrl, this.ioTargetModels);
        },
        getOSDIDs: function() {
            // create a fake model that mimics the interfaces we need
            var reqres = this.App.ReqRes;
            var model = {};
            model.fetchMetrics = function(hostname) {
                var d = $.Deferred();
                setTimeout(function() {
                    var resp = reqres.request('get:osdids', hostname);
                    model.ids = resp;
                    d.resolve(resp);
                }, 0);
                return d.promise();
            };
            model.keys = function() {
                return model.ids;
            };
            return model;
        },
        makeHostDeviceDiskSpaceBytes: function(hostname) {
            return this.makePerHostGraphs(hostname, this.makeDiskSpaceBytesGraphUrl, this.getOSDIDs());
        },
        makeHostDeviceDiskSpaceInodes: function(hostname) {
            return this.makePerHostGraphs(hostname, this.makeDiskSpaceInodesGraphUrl, this.getOSDIDs());
        },
        showButtons: function() {
            this.ui.buttons.css('visibility', 'visible');
        },
        hideButtons: function() {
            this.ui.buttons.css('visibility', 'hidden');
        },
        makePerHostGraphs: function(hostname, fn, model) {
            var self = this;
            this.hostname = hostname;
            var deferred = $.Deferred();
            model.fetchMetrics(hostname).done(function() {
                var list = model.keys();
                deferred.resolve(_.map(list, function(cpuid) {
                    return fn.call(self, hostname, cpuid);
                }));
            }).fail(function(resp) {
                deferred.reject(resp);
            });
            return deferred.promise();
        },
        makeHostUrls: function(fn) {
            return function() {
                var hosts = this.App.ReqRes.request('get:hosts');
                return _.map(hosts, function(host) {
                    return fn(host);
                });
            };
        },
        selectors: ['0-1', '0-2', '1-1', '1-2', '2-1', '2-2', '3-1', '3-2', '4-1', '4-2'],
        imageLoader: function($el, url) {
            setTimeout(function() {
                $el.html('');
                var image = new Image();
                image.src = url;
                image.onload = function() {
                    $el.html(image);
                };
                image.onerror = function() {
                    $el.html('');
                };
            }, 0);
        },
        makeHostOverviewGraphUrl: function(host) {
            return function() {
                return [this.makeCPUGraphUrl(host), this.makeLoadAvgGraphUrl(host), this.makeMemoryGraphUrl(host)];
            };
        },
        hideGraphs: function() {
            this.$('.graph-card').css('visibility', 'hidden');
        },
        populateAll: function(title, fn) {
            var urls = fn.call(this);
            var self = this;
            this.ui.title.text(title);
            _.each(urls, function(url, index) {
                var $graph = self.$('.graph' + self.selectors[index]);
                $graph.css('visibility', 'visible');
                self.imageLoader($graph, url);
            });
        }
    });

    return GraphwallView;
});
<commit_msg>Re-delegate events after render.<commit_after>/*global define*/

define(['jquery', 'underscore', 'backbone', 'templates', 'helpers/graph-utils', 'models/application-model', 'marionette'], function($, _, Backbone, JST, gutils, models) {
    'use strict';

    var GraphwallView = Backbone.Marionette.ItemView.extend({
        template: JST['app/scripts/templates/graphwall-view.ejs'],
        className: 'graph-mode span12',
        ui: {
            'title': '.title',
            'buttons': '.btn-graph'
        },
        events: {
            'click .btn-graph .btn': 'clickHandler'
        },
        clickHandler: function(evt) {
            var $target = $(evt.target);
            var id = $target.attr('data-id');
            var route = 'graph/' + this.hostname + '/' + id;
            if (id === 'overview') {
                route = 'graph/' + this.hostname;
            }
            console.log(route);
            this.AppRouter.navigate(route, {
                trigger: true
            });
        },
        graphs: [{
            metrics: ['byte_avail', 'byte_free', 'byte_used'],
            fn: 'makeDiskSpaceBytesGraphUrl',
            util: 'makeDiskSpaceTargets'
        }, {
            metrics: ['inodes_avail', 'inodes_free', 'inodes_used'],
            fn: 'makeDiskSpaceInodesGraphUrl',
            util: 'makeDiskSpaceTargets'
        }, {
            metrics: ['system', 'user', 'idle'],
            fn: 'makeCPUGraphUrl',
            util: 'makeCPUTargets'
        }, {
            metrics: ['system', 'user', 'nice', 'idle', 'iowait', 'irq', 'softirq', 'steal'],
            fn: 'makeCPUDetailGraphUrl',
            util: 'makeCPUDetailedTargets'
        }, {
            metrics: ['op_r_latency', 'op_w_latency', 'op_rw_latency'],
            fn: 'makeOpsLatencyGraphUrl',
            util: 'makeOpLatencyTargets'
        }, {
            metrics: ['journal_ops', 'journal_wr'],
            fn: 'makeJournalOpsGraphUrl',
            util: 'makeFilestoreTargets'
        }, {
            metrics: ['01', '05', '15'],
            fn: 'makeLoadAvgGraphUrl',
            util: 'makeLoadAvgTargets'
        }, {
            metrics: ['Active', 'Buffers', 'Cached', 'MemFree'],
            fn: 'makeMemoryGraphUrl',
            util: 'makeMemoryTargets'
        }, {
            metrics: ['read_byte_per_second', 'write_byte_per_second'],
            fn: 'makeHostDeviceRWBytesGraphUrl',
            util: 'makeIOStatIOPSTargets'
        }, {
            metrics: ['read_await', 'write_await'],
            fn: 'makeHostDeviceRWAwaitGraphUrl',
            util: 'makeIOStatIOPSTargets'
        }, {
            metrics: ['iops'],
            fn: 'makeHostDeviceIOPSGraphUrl',
            util: 'makeIOStatIOPSTargets'
        }],
        makeGraphFunctions: function(options) {
            var targets = gutils.makeTargets(gutils[options.util](options.metrics));
            this[options.fn] = gutils.makeGraphURL('png', this.baseUrl, this.heightWidth, targets);
        },
        initialize: function() {
            this.App = Backbone.Marionette.getOption(this, 'App');
            this.AppRouter = Backbone.Marionette.getOption(this, 'AppRouter');
            this.graphiteHost = Backbone.Marionette.getOption(this, 'graphiteHost');
            this.baseUrl = gutils.makeBaseUrl(this.graphiteHost);
            this.heightWidth = gutils.makeHeightWidthParams(442, 266);
            _.bindAll(this, 'makeGraphFunctions', 'postRender');

            this.listenTo(this, 'render', this.postRender);

            _.each(this.graphs, this.makeGraphFunctions);

            this.cpuTargetModels = new models.GraphiteCPUModel(undefined, {
                graphiteHost: this.graphiteHost
            });
            this.ioTargetModels = new models.GraphiteIOModel(undefined, {
                graphiteHost: this.graphiteHost
            });
        },
        postRender: function() {
            this.delegateEvents(this.events);
        },
        makeCPUDetail: function(hostname) {
            return this.makePerHostGraphs(hostname, this.makeCPUDetailGraphUrl, this.cpuTargetModels);
        },
        makeHostDeviceIOPS: function(hostname) {
            return this.makePerHostGraphs(hostname, this.makeHostDeviceIOPSGraphUrl, this.ioTargetModels);
        },
        makeHostDeviceRWBytes: function(hostname) {
            return this.makePerHostGraphs(hostname, this.makeHostDeviceRWBytesGraphUrl, this.ioTargetModels);
        },
        makeHostDeviceRWAwait: function(hostname) {
            return this.makePerHostGraphs(hostname, this.makeHostDeviceRWAwaitGraphUrl, this.ioTargetModels);
        },
        getOSDIDs: function() {
            // create a fake model that mimics the interfaces we need
            var reqres = this.App.ReqRes;
            var model = {};
            model.fetchMetrics = function(hostname) {
                var d = $.Deferred();
                setTimeout(function() {
                    var resp = reqres.request('get:osdids', hostname);
                    model.ids = resp;
                    d.resolve(resp);
                }, 0);
                return d.promise();
            };
            model.keys = function() {
                return model.ids;
            };
            return model;
        },
        makeHostDeviceDiskSpaceBytes: function(hostname) {
            return this.makePerHostGraphs(hostname, this.makeDiskSpaceBytesGraphUrl, this.getOSDIDs());
        },
        makeHostDeviceDiskSpaceInodes: function(hostname) {
            return this.makePerHostGraphs(hostname, this.makeDiskSpaceInodesGraphUrl, this.getOSDIDs());
        },
        showButtons: function() {
            this.ui.buttons.css('visibility', 'visible');
        },
        hideButtons: function() {
            this.ui.buttons.css('visibility', 'hidden');
        },
        makePerHostGraphs: function(hostname, fn, model) {
            var self = this;
            this.hostname = hostname;
            var deferred = $.Deferred();
            model.fetchMetrics(hostname).done(function() {
                var list = model.keys();
                deferred.resolve(_.map(list, function(cpuid) {
                    return fn.call(self, hostname, cpuid);
                }));
            }).fail(function(resp) {
                deferred.reject(resp);
            });
            return deferred.promise();
        },
        makeHostUrls: function(fn) {
            return function() {
                var hosts = this.App.ReqRes.request('get:hosts');
                return _.map(hosts, function(host) {
                    return fn(host);
                });
            };
        },
        selectors: ['0-1', '0-2', '1-1', '1-2', '2-1', '2-2', '3-1', '3-2', '4-1', '4-2'],
        imageLoader: function($el, url) {
            setTimeout(function() {
                $el.html('');
                var image = new Image();
                image.src = url;
                image.onload = function() {
                    $el.html(image);
                };
                image.onerror = function() {
                    $el.html('');
                };
            }, 0);
        },
        makeHostOverviewGraphUrl: function(host) {
            return function() {
                return [this.makeCPUGraphUrl(host), this.makeLoadAvgGraphUrl(host), this.makeMemoryGraphUrl(host)];
            };
        },
        hideGraphs: function() {
            this.$('.graph-card').css('visibility', 'hidden');
        },
        populateAll: function(title, fn) {
            var urls = fn.call(this);
            var self = this;
            this.ui.title.text(title);
            _.each(urls, function(url, index) {
                var $graph = self.$('.graph' + self.selectors[index]);
                $graph.css('visibility', 'visible');
                self.imageLoader($graph, url);
            });
        }
    });

    return GraphwallView;
});
<|endoftext|>


<commit_before>import fs from 'fs';
import { parseModule } from '../../';
import { parseScript } from '../../';
import expect from 'expect.js';

let scriptDir = 'node_modules/test262-parser-tests';

function parse(src, isModule, earlyErrors) {
  (isModule ? parseModule : parseScript)(src, { earlyErrors });
}

suite('test262', () => {
  suite('pass and pass-explicit', () => {
    let passExcludes = [
      // https://github.com/shapesecurity/shift-parser-js/issues/311
      '995.script.js',

      // This is an invalid test
      '970.script.js',

      // https://github.com/shapesecurity/shift-parser-js/issues/311
      '1012.script.js'
    ];
    fs.readdirSync(`${scriptDir}/pass`)
      .filter(item => passExcludes.indexOf(item) === -1)
      .forEach(f => {
        let passTree, passExplicitTree;
        let passTestDir = `${scriptDir}/pass/${f}`;
        let passExplicitTestDir = `${scriptDir}/pass-explicit/${f}`;
        test(`does not throw error and generates same tree[${f}]`, () => {
          let passSrc = fs.readFileSync(passTestDir, 'utf8');
          expect(function parsePass() {
            passTree = parse(passSrc, f.match('.module.js'), true);
          }).to.not.throwError();

          let passExplicitSrc = fs.readFileSync(passExplicitTestDir, 'utf8');
          expect(function parsePassExplicit() {
            passExplicitTree = parse(passExplicitSrc, f.match('.module.js'), true);
          }).to.not.throwError();

          expect.eql(passTree, passExplicitTree);
        });
      });
  });

  suite('fail', () => {
    let failTestDir = `${scriptDir}/fail`;
    let failExcludes = [
      // https://github.com/shapesecurity/shift-parser-js/issues/313
      '69.script.js',
      '70.script.js',
      '71.script.js',
      '75.script.js',
      '76.script.js',
      '77.script.js',
      '149.script.js',
      '151.script.js',
      '248.script.js',
      '519.script.js'
    ];
    fs.readdirSync(failTestDir)
      .filter(item => failExcludes.indexOf(item) === -1)
      .forEach(f => {
        test(`throws error[${f}]`, () => {
          let src = fs.readFileSync(`${failTestDir}/${f}`, 'utf8');
          expect(() => {
            parse(src, f.match('.module.js'), false);
          }).to.throwError();
        });
      });
  });

  suite('early', () => {
    let earlyExcludes = [
      // https://github.com/shapesecurity/shift-parser-js/issues/316
      '56.script.js', '641.script.js', '642.script.js',

      // https://github.com/shapesecurity/shift-parser-js/issues/317
      '88.script.js', '90.script.js',

      // https://github.com/shapesecurity/shift-parser-js/issues/318
      '190.script.js', '205.script.js',

      // https://github.com/shapesecurity/shift-parser-js/issues/319
      '557.script.js',

      // https://github.com/shapesecurity/shift-parser-js/issues/320
      '558.script.js', '559.script.js', '560.script.js', '561.script.js',

      // https://github.com/shapesecurity/shift-parser-js/issues/321
      '563.script.js', '564.script.js', '565.script.js', '566.script.js',
      '567.script.js', '568.script.js', '569.script.js', '570.script.js',
      '571.script.js', '572.script.js', '574.script.js',

      // https://github.com/shapesecurity/shift-parser-js/issues/322
      '575.script.js', '576.script.js', '577.script.js', '578.script.js',
      '579.script.js', '580.script.js', '581.script.js', '582.script.js',
      '583.script.js', '585.script.js', '586.script.js', '587.script.js', '588.script.js',

      // https://github.com/shapesecurity/shift-parser-js/issues/323
      '589.script.js', '590.script.js', '591.script.js', '592.script.js', '593.script.js',

      // https://github.com/tc39/test262-parser-tests/issues/7
      '594.script.js', '596.script.js', '597.script.js', '598.script.js',

      // https://github.com/tc39/test262-parser-tests/issues/6
      '135.script.js',

      // causes Syntax Errors in the test script
      '599.script.js', '600.script.js', '601.script.js', '602.script.js'
    ];
    let earlyErrorsTestDir = `${scriptDir}/early`;
    fs.readdirSync(earlyErrorsTestDir)
      .filter(item => earlyExcludes.indexOf(item) === -1)
      .forEach(f => {
        let src = fs.readFileSync(`${earlyErrorsTestDir}/${f}`, 'utf8');
        test(`does not throw error with earlyErrors false[${f}]`, function () {
          expect(() => {
            parse(src, f.match('.module.js'), false);
          }).to.not.throwError();
        });
        test(`throws error with earlyErrors true[${f}]`, function () {
          expect(() => {
            parse(src, f.match('.module.js'), true);
          }).to.throwError();
        });
      });
  });
});
<commit_msg>Add location sanity check to test262-parser-tests<commit_after>import fs from 'fs';
import { parseScriptWithLocation, parseModuleWithLocation } from '../../';
import { locationSanityCheck } from '../helpers';
import expect from 'expect.js';

let scriptDir = 'node_modules/test262-parser-tests';

function parse(src, isModule, earlyErrors) {
  return (isModule ? parseModuleWithLocation : parseScriptWithLocation)(src, { earlyErrors });
}

suite('test262', () => {
  suite('pass and pass-explicit', () => {
    let passExcludes = [
      // https://github.com/shapesecurity/shift-parser-js/issues/311
      '995.script.js',

      // This is an invalid test
      '970.script.js',

      // https://github.com/shapesecurity/shift-parser-js/issues/311
      '1012.script.js'
    ];
    fs.readdirSync(`${scriptDir}/pass`)
      .filter(item => passExcludes.indexOf(item) === -1)
      .forEach(f => {
        let passTree, passLocations, passExplicitTree;
        let passTestDir = `${scriptDir}/pass/${f}`;
        let passExplicitTestDir = `${scriptDir}/pass-explicit/${f}`;
        test(`does not throw error and generates same tree[${f}]`, () => {
          let passSrc = fs.readFileSync(passTestDir, 'utf8');
          expect(function parsePass() {
            ({tree: passTree, locations: passLocations} = parse(passSrc, f.match('.module.js'), true));
          }).to.not.throwError();
          locationSanityCheck(passTree, passLocations);

          let passExplicitSrc = fs.readFileSync(passExplicitTestDir, 'utf8');
          expect(function parsePassExplicit() {
            passExplicitTree = parse(passExplicitSrc, f.match('.module.js'), true).tree;
          }).to.not.throwError();

          expect.eql(passTree, passExplicitTree);
        });
      });
  });

  suite('fail', () => {
    let failTestDir = `${scriptDir}/fail`;
    let failExcludes = [
      // https://github.com/shapesecurity/shift-parser-js/issues/313
      '69.script.js',
      '70.script.js',
      '71.script.js',
      '75.script.js',
      '76.script.js',
      '77.script.js',
      '149.script.js',
      '151.script.js',
      '248.script.js',
      '519.script.js'
    ];
    fs.readdirSync(failTestDir)
      .filter(item => failExcludes.indexOf(item) === -1)
      .forEach(f => {
        test(`throws error[${f}]`, () => {
          let src = fs.readFileSync(`${failTestDir}/${f}`, 'utf8');
          expect(() => {
            parse(src, f.match('.module.js'), false);
          }).to.throwError();
        });
      });
  });

  suite('early', () => {
    let earlyExcludes = [
      // https://github.com/shapesecurity/shift-parser-js/issues/316
      '56.script.js', '641.script.js', '642.script.js',

      // https://github.com/shapesecurity/shift-parser-js/issues/317
      '88.script.js', '90.script.js',

      // https://github.com/shapesecurity/shift-parser-js/issues/318
      '190.script.js', '205.script.js',

      // https://github.com/shapesecurity/shift-parser-js/issues/319
      '557.script.js',

      // https://github.com/shapesecurity/shift-parser-js/issues/320
      '558.script.js', '559.script.js', '560.script.js', '561.script.js',

      // https://github.com/shapesecurity/shift-parser-js/issues/321
      '563.script.js', '564.script.js', '565.script.js', '566.script.js',
      '567.script.js', '568.script.js', '569.script.js', '570.script.js',
      '571.script.js', '572.script.js', '574.script.js',

      // https://github.com/shapesecurity/shift-parser-js/issues/322
      '575.script.js', '576.script.js', '577.script.js', '578.script.js',
      '579.script.js', '580.script.js', '581.script.js', '582.script.js',
      '583.script.js', '585.script.js', '586.script.js', '587.script.js', '588.script.js',

      // https://github.com/shapesecurity/shift-parser-js/issues/323
      '589.script.js', '590.script.js', '591.script.js', '592.script.js', '593.script.js',

      // https://github.com/tc39/test262-parser-tests/issues/7
      '594.script.js', '596.script.js', '597.script.js', '598.script.js',

      // https://github.com/tc39/test262-parser-tests/issues/6
      '135.script.js',

      // causes Syntax Errors in the test script
      '599.script.js', '600.script.js', '601.script.js', '602.script.js'
    ];
    let earlyErrorsTestDir = `${scriptDir}/early`;
    fs.readdirSync(earlyErrorsTestDir)
      .filter(item => earlyExcludes.indexOf(item) === -1)
      .forEach(f => {
        let src = fs.readFileSync(`${earlyErrorsTestDir}/${f}`, 'utf8');
        test(`does not throw error with earlyErrors false[${f}]`, function () {
          expect(() => {
            parse(src, f.match('.module.js'), false);
          }).to.not.throwError();
        });
        test(`throws error with earlyErrors true[${f}]`, function () {
          expect(() => {
            parse(src, f.match('.module.js'), true);
          }).to.throwError();
        });
      });
  });
});
<|endoftext|>


<commit_before>'use strict';

/**
 * Tests for init system for Node.js.
 * (C) 2015 Alex Fernández.
 */

// requires
require('prototypes');
var Log = require('log');
var testing = require('testing');
var inits = require('../lib/initSystem.js');

// globals
var log = new Log('info');

function testInitSystem(callback)
{
	var system = new inits.InitSystem();
	system.options.exitProcess = false;
	var witness = {};
	system.on('error', function(error)
	{
		testing.failure(error, callback);
	});
	system.init(function(next)
	{
		witness.init = true;
		log.debug('init');
		next(null);
	});
	system.start(function(next)
	{
		testing.assert(witness.init, 'Should call init', callback);
		witness.start = true;
		log.debug('start');
		next(null);
	});
	system.on('ready', function()
	{
		testing.assert(witness.start, 'Should call start', callback);
		system.shutdown();
	});
	system.stop(function(next)
	{
		testing.assert(witness.start, 'Should call start', callback);
		witness.stop = true;
		log.debug('stop');
		next(null);
	});
	system.finish(function(next)
	{
		testing.assert(witness.stop, 'Should call stop', callback);
		witness.finish = true;
		log.debug('finish');
		next(null);
	});
	system.on('end', function()
	{
		testing.assert(witness.finish, 'Should call finish', callback);
		testing.success(callback);
	});
}

function testStandalone(callback)
{
	var system = new inits.InitSystem();
	system.options.exitProcess = false;
	var witness = {};
	system.on('error', function(error)
	{
		testing.failure(error, callback);
	});
	system.init(function(next)
	{
		witness.init = true;
		log.debug('init');
		next(null);
	});
	system.standalone(function(next)
	{
		testing.assert(witness.init, 'Should call init', callback);
		witness.standalone = true;
		log.debug('standalone');
		next(null);
	});
	system.finish(function(next)
	{
		testing.assert(witness.standalone, 'Should call standalone', callback);
		witness.finish = true;
		log.debug('finish');
		next(null);
	});
	system.on('end', function()
	{
		testing.assert(witness.finish, 'Should call finish', callback);
		testing.success(callback);
	});
}

function testSeveralTasks(callback)
{
	var system = new inits.InitSystem();
	system.options.exitProcess = false;
	var witness = {};
	system.on('error', function(error)
	{
		testing.failure(error, callback);
	});
	system.init(function(next)
	{
		witness.init1 = true;
		log.debug('init1');
		next(null);
	});
	system.init(function(next)
	{
		witness.init2 = true;
		log.debug('init2');
		next(null);
	});
	system.standalone(function(next)
	{
		testing.assert(witness.init1, 'Should call init1', callback);
		testing.assert(witness.init2, 'Should call init2', callback);
		witness.standalone = true;
		log.debug('standalone');
		next();
	});
	system.finish(function(next)
	{
		witness.finish1 = true;
		log.debug('finish1');
		next(null);
	});
	system.finish(function(next)
	{
		witness.finish2 = true;
		log.debug('finish2');
		next(null);
	});
	system.on('end', function()
	{
		testing.assert(witness.finish1, 'Should call finish1', callback);
		testing.assert(witness.finish2, 'Should call finish2', callback);
		testing.success(callback);
	});
}

function testErrors(callback)
{
	var system = new inits.InitSystem();
	system.options.exitProcess = false;
	system.options.showErrors = false;
	system.options.stopOnError = true;
	var init1 = false;
	system.on('error', function(error)
	{
		if (error.contains('init1'))
		{
			init1 = true;
			return;
		}
		else if (error.contains('finish1'))
		{
			testing.assert(init1, 'Should catch init1 error', callback);
			testing.success(callback);
		}
		else
		{
			testing.failure('Invalid error ' + error);
		}
	});
	system.init(function(next)
	{
		next('init1');
	});
	system.init(function(next)
	{
		next('init2');
	});
	system.start(function(next)
	{
		next('start');
	});
	system.finish(function(next)
	{
		next('finish1');
	});
	system.finish(function(next)
	{
		next('finish2');
	});
}

function testErrorWithoutListener(callback)
{
	var system = new inits.InitSystem();
	system.options.exitProcess = false;
	system.options.showErrors = false;
	system.options.stopOnError = true;
	var finish = false;
	system.init(function(next)
	{
		next('init1');
	});
	system.finish(function(next)
	{
		finish = true;
		next(null);
	});
	system.on('end', function()
	{
		testing.assert(finish, 'Should have finished', callback);
		testing.success(callback);
	});
}

/**
 * Run all tests.
 */
exports.test = function(callback)
{
	testing.run([
		testInitSystem,
		testStandalone,
		testSeveralTasks,
		testErrors,
		testErrorWithoutListener,
	], callback);
};

// run tests if invoked directly
if (__filename == process.argv[1])
{
	log = new Log('debug');
	inits.standalone(testing.toShow(exports.test));
}

<commit_msg>Improved error message.<commit_after>'use strict';

/**
 * Tests for init system for Node.js.
 * (C) 2015 Alex Fernández.
 */

// requires
require('prototypes');
var Log = require('log');
var testing = require('testing');
var inits = require('../lib/initSystem.js');

// globals
var log = new Log('info');

function testInitSystem(callback)
{
	var system = new inits.InitSystem();
	system.options.exitProcess = false;
	var witness = {};
	system.on('error', function(error)
	{
		testing.failure(error, callback);
	});
	system.init(function(next)
	{
		witness.init = true;
		log.debug('init');
		next(null);
	});
	system.start(function(next)
	{
		testing.assert(witness.init, 'Should call init', callback);
		witness.start = true;
		log.debug('start');
		next(null);
	});
	system.on('ready', function()
	{
		testing.assert(witness.start, 'Should call start', callback);
		system.shutdown();
	});
	system.stop(function(next)
	{
		testing.assert(witness.start, 'Should call start', callback);
		witness.stop = true;
		log.debug('stop');
		next(null);
	});
	system.finish(function(next)
	{
		testing.assert(witness.stop, 'Should call stop', callback);
		witness.finish = true;
		log.debug('finish');
		next(null);
	});
	system.on('end', function()
	{
		testing.assert(witness.finish, 'Should call finish', callback);
		testing.success(callback);
	});
}

function testStandalone(callback)
{
	var system = new inits.InitSystem();
	system.options.exitProcess = false;
	var witness = {};
	system.on('error', function(error)
	{
		testing.failure(error, callback);
	});
	system.init(function(next)
	{
		witness.init = true;
		log.debug('init');
		next(null);
	});
	system.standalone(function(next)
	{
		testing.assert(witness.init, 'Should call init', callback);
		witness.standalone = true;
		log.debug('standalone');
		next(null);
	});
	system.finish(function(next)
	{
		testing.assert(witness.standalone, 'Should call standalone', callback);
		witness.finish = true;
		log.debug('finish');
		next(null);
	});
	system.on('end', function()
	{
		testing.assert(witness.finish, 'Should call finish', callback);
		testing.success(callback);
	});
}

function testSeveralTasks(callback)
{
	var system = new inits.InitSystem();
	system.options.exitProcess = false;
	var witness = {};
	system.on('error', function(error)
	{
		testing.failure(error, callback);
	});
	system.init(function(next)
	{
		witness.init1 = true;
		log.debug('init1');
		next(null);
	});
	system.init(function(next)
	{
		witness.init2 = true;
		log.debug('init2');
		next(null);
	});
	system.standalone(function(next)
	{
		testing.assert(witness.init1, 'Should call init1', callback);
		testing.assert(witness.init2, 'Should call init2', callback);
		witness.standalone = true;
		log.debug('standalone');
		next();
	});
	system.finish(function(next)
	{
		witness.finish1 = true;
		log.debug('finish1');
		next(null);
	});
	system.finish(function(next)
	{
		witness.finish2 = true;
		log.debug('finish2');
		next(null);
	});
	system.on('end', function()
	{
		testing.assert(witness.finish1, 'Should call finish1', callback);
		testing.assert(witness.finish2, 'Should call finish2', callback);
		testing.success(callback);
	});
}

function testErrors(callback)
{
	var system = new inits.InitSystem();
	system.options.exitProcess = false;
	system.options.showErrors = false;
	system.options.stopOnError = true;
	var init1 = false;
	system.on('error', function(error)
	{
		if (error.contains('init1'))
		{
			init1 = true;
			return;
		}
		else if (error.contains('finish1'))
		{
			testing.assert(init1, 'Should catch init1 error', callback);
			testing.success(callback);
		}
		else
		{
			testing.failure('Invalid error: ' + error);
		}
	});
	system.init(function(next)
	{
		next('init1');
	});
	system.init(function(next)
	{
		next('init2');
	});
	system.start(function(next)
	{
		next('start');
	});
	system.finish(function(next)
	{
		next('finish1');
	});
	system.finish(function(next)
	{
		next('finish2');
	});
}

function testErrorWithoutListener(callback)
{
	var system = new inits.InitSystem();
	system.options.exitProcess = false;
	system.options.showErrors = false;
	system.options.stopOnError = true;
	var finish = false;
	system.init(function(next)
	{
		next('init1');
	});
	system.finish(function(next)
	{
		finish = true;
		next(null);
	});
	system.on('end', function()
	{
		testing.assert(finish, 'Should have finished', callback);
		testing.success(callback);
	});
}

/**
 * Run all tests.
 */
exports.test = function(callback)
{
	testing.run([
		testInitSystem,
		testStandalone,
		testSeveralTasks,
		testErrors,
		testErrorWithoutListener,
	], callback);
};

// run tests if invoked directly
if (__filename == process.argv[1])
{
	log = new Log('debug');
	inits.standalone(testing.toShow(exports.test));
}

<|endoftext|>


<commit_before>const { indexOf } = require( 'lodash' )
const ConfigLoader = require( 'easy/core/ConfigLoader' )
const { Application } = require( 'easy/core' )
const { SecurityAccess } = require( 'easy/interfaces' )
const roles = ConfigLoader.loadFromGlobal( 'roles' )

/**
 * @class Access
 * @extends SecurityAccess
 */
class Access extends SecurityAccess {
    /**
     * constructor
     *
     * @param  {Container} container
     */
    constructor( container ) {
        super()

        this.loadRoles()
        this._restrictions = {}
        this.container = container
    }

    /**
     * getAccessHandler - returns access authority handler
     *
     * @param  {Object} configurations
     * @returns {Access|Service}
     */
    getAccessHandler( configurations ) {
        return 'default' === configurations.strategy ? this : this.container.get( configurations.strategy )
    }

    /**
     * loadRoles - load roles config
     */
    loadRoles() {
        for ( let role in roles ) {
            this[ role ] = roles[ role ]
        }
    }

    /**
     * focusOn - specify the focus field to focus on
     *
     * @param  {string|number} focus
     * @returns {Access}
     */
    focusOn( focus ) {
        this._focus = focus

        return this
    }

    /**
     * restrict - define rules
     *
     * @param  {Array} { mustBe = []
     * @param  {Array} canCreate = []
     * @param  {Array} canRead = []
     * @param  {Array} canUpdate = []
     * @param  {Array} canDelete = [] }
     * @returns {Access}
     */
    restrict({ mustBe = [], canCreate = [], canRead = [], canUpdate = [], canDelete = [] }) {
        if ( !mustBe || 0 === mustBe.length ) {
            mustBe = [ this.any ]
        }

        if ( !canCreate || 0 === canCreate.length ) {
            canCreate = mustBe
        }

        if ( !canRead || 0 === canRead.length ) {
            canRead = mustBe
        }

        if ( !canUpdate || 0 === canUpdate.length ) {
            canUpdate = mustBe
        }

        if ( !canDelete || 0 === canDelete.length ) {
            canDelete = mustBe
        }

        this.restrictions = {
            mustBe,
            canCreate,
            canRead,
            canUpdate,
            canDelete
        }

        return this
    }

    /**
     * authorized - check if user is authorized to access to the route requested
     *
     * @param  {Object} { configurations
     * @param  {Request} request
     * @param  {Response} response
     * @param  {Container} container }
     * @returns {Promise}
     */
    authorized({ configurations, request, response, container }) {
        let isAuthorizedToAccess = false
        let authorized = false
        const method = request.getMethod().toLowerCase()
        const user = request.getAppParameter( 'user' )

        this.restrict( configurations.rules ).focusOn( user[ configurations.focus ])

        authorized = indexOf( this.restrictions.mustBe, this.focus ) !== -1 || indexOf( this.restrictions.mustBe, this.any ) !== -1

        if ( authorized ) {

            const methodWhenReading = [ 'get', 'head', 'options', 'trace' ]
            const methodWhenCreating = [ 'post' ]
            const methodWhenUpdating = [ 'put', 'patch' ]
            const methodWhenDeleting = [ 'delete' ]

            if ( indexOf( methodWhenReading, method ) !== -1 ) {

                isAuthorizedToAccess = indexOf( this.restrictions.canRead, this.focus ) !== -1 || indexOf( this.restrictions.canRead, this.any ) !== -1

            } else if ( indexOf( methodWhenCreating, method ) !== -1 ) {

                isAuthorizedToAccess = indexOf( this.restrictions.canCreate, this.focus ) !== -1 || indexOf( this.restrictions.canCreate, this.any ) !== -1

            } else if ( indexOf( methodWhenUpdating, method ) !== -1 ) {

                isAuthorizedToAccess = indexOf( this.restrictions.canUpdate, this.focus ) !== -1 || indexOf( this.restrictions.canUpdate, this.any ) !== -1

            } else if ( indexOf( methodWhenDeleting, method ) !== -1 ) {

                isAuthorizedToAccess = indexOf( this.restrictions.canDelete, this.focus ) !== -1 || indexOf( this.restrictions.canDelete, this.any ) !== -1

            }

        }

        return isAuthorizedToAccess ? Promise.resolve() : Promise.reject()
    }

    /**
     * get - role focused
     *
     * @returns {string|number}
     */
    get focus() {
        return this._focus
    }

    /**
     * get - restrictions
     *
     * @returns {Object}
     */
    get restrictions() {
        return this._restrictions
    }

    /**
     * set - restrictions
     *
     * @param  {Object} restrictions
     * @returns {Access}
     */
    set restrictions( restrictions ) {
        this._restrictions = restrictions
        return this
    }
}

module.exports = Access
<commit_msg>Remove Application import<commit_after>const { indexOf } = require( 'lodash' )
const ConfigLoader = require( 'easy/core/ConfigLoader' )
const { SecurityAccess } = require( 'easy/interfaces' )
const roles = ConfigLoader.loadFromGlobal( 'roles' )

/**
 * @class Access
 * @extends SecurityAccess
 */
class Access extends SecurityAccess {
    /**
     * constructor
     *
     * @param  {Container} container
     */
    constructor( container ) {
        super()

        this.loadRoles()
        this._restrictions = {}
        this.container = container
    }

    /**
     * getAccessHandler - returns access authority handler
     *
     * @param  {Object} configurations
     * @returns {Access|Service}
     */
    getAccessHandler( configurations ) {
        return 'default' === configurations.strategy ? this : this.container.get( configurations.strategy )
    }

    /**
     * loadRoles - load roles config
     */
    loadRoles() {
        for ( let role in roles ) {
            this[ role ] = roles[ role ]
        }
    }

    /**
     * focusOn - specify the focus field to focus on
     *
     * @param  {string|number} focus
     * @returns {Access}
     */
    focusOn( focus ) {
        this._focus = focus

        return this
    }

    /**
     * restrict - define rules
     *
     * @param  {Array} { mustBe = []
     * @param  {Array} canCreate = []
     * @param  {Array} canRead = []
     * @param  {Array} canUpdate = []
     * @param  {Array} canDelete = [] }
     * @returns {Access}
     */
    restrict({ mustBe = [], canCreate = [], canRead = [], canUpdate = [], canDelete = [] }) {
        if ( !mustBe || 0 === mustBe.length ) {
            mustBe = [ this.any ]
        }

        if ( !canCreate || 0 === canCreate.length ) {
            canCreate = mustBe
        }

        if ( !canRead || 0 === canRead.length ) {
            canRead = mustBe
        }

        if ( !canUpdate || 0 === canUpdate.length ) {
            canUpdate = mustBe
        }

        if ( !canDelete || 0 === canDelete.length ) {
            canDelete = mustBe
        }

        this.restrictions = {
            mustBe,
            canCreate,
            canRead,
            canUpdate,
            canDelete
        }

        return this
    }

    /**
     * authorized - check if user is authorized to access to the route requested
     *
     * @param  {Object} { configurations
     * @param  {Request} request
     * @param  {Response} response
     * @param  {Container} container }
     * @returns {Promise}
     */
    authorized({ configurations, request, response, container }) {
        let isAuthorizedToAccess = false
        let authorized = false
        const method = request.getMethod().toLowerCase()
        const user = request.getAppParameter( 'user' )

        this.restrict( configurations.rules ).focusOn( user[ configurations.focus ])

        authorized = indexOf( this.restrictions.mustBe, this.focus ) !== -1 || indexOf( this.restrictions.mustBe, this.any ) !== -1

        if ( authorized ) {

            const methodWhenReading = [ 'get', 'head', 'options', 'trace' ]
            const methodWhenCreating = [ 'post' ]
            const methodWhenUpdating = [ 'put', 'patch' ]
            const methodWhenDeleting = [ 'delete' ]

            if ( indexOf( methodWhenReading, method ) !== -1 ) {

                isAuthorizedToAccess = indexOf( this.restrictions.canRead, this.focus ) !== -1 || indexOf( this.restrictions.canRead, this.any ) !== -1

            } else if ( indexOf( methodWhenCreating, method ) !== -1 ) {

                isAuthorizedToAccess = indexOf( this.restrictions.canCreate, this.focus ) !== -1 || indexOf( this.restrictions.canCreate, this.any ) !== -1

            } else if ( indexOf( methodWhenUpdating, method ) !== -1 ) {

                isAuthorizedToAccess = indexOf( this.restrictions.canUpdate, this.focus ) !== -1 || indexOf( this.restrictions.canUpdate, this.any ) !== -1

            } else if ( indexOf( methodWhenDeleting, method ) !== -1 ) {

                isAuthorizedToAccess = indexOf( this.restrictions.canDelete, this.focus ) !== -1 || indexOf( this.restrictions.canDelete, this.any ) !== -1

            }

        }

        return isAuthorizedToAccess ? Promise.resolve() : Promise.reject()
    }

    /**
     * get - role focused
     *
     * @returns {string|number}
     */
    get focus() {
        return this._focus
    }

    /**
     * get - restrictions
     *
     * @returns {Object}
     */
    get restrictions() {
        return this._restrictions
    }

    /**
     * set - restrictions
     *
     * @param  {Object} restrictions
     * @returns {Access}
     */
    set restrictions( restrictions ) {
        this._restrictions = restrictions
        return this
    }
}

module.exports = Access
<|endoftext|>


<commit_before>/**
 * @fileoverview Defines environment settings and globals.
 * @author Elan Shanker
 */
"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const globals = require("globals");

//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------

module.exports = {
    builtin: {
        globals: globals.es5
    },
    browser: {

        /*
         * For backward compatibility.
         * Remove those on the next major release.
         */
        globals: Object.assign(
            {
                AutocompleteErrorEvent: false,
                CDATASection: false,
                ClientRect: false,
                ClientRectList: false,
                CSSAnimation: false,
                CSSTransition: false,
                CSSUnknownRule: false,
                CSSViewportRule: false,
                Debug: false,
                DocumentTimeline: false,
                DOMSettableTokenList: false,
                ElementTimeControl: false,
                FederatedCredential: false,
                FileError: false,
                HTMLAppletElement: false,
                HTMLBlockquoteElement: false,
                HTMLIsIndexElement: false,
                HTMLKeygenElement: false,
                HTMLLayerElement: false,
                IDBEnvironment: false,
                InputMethodContext: false,
                MediaKeyError: false,
                MediaKeyEvent: false,
                MediaKeys: false,
                opera: false,
                PasswordCredential: false,
                ReadableByteStream: false,
                SharedKeyframeList: false,
                showModalDialog: false,
                SiteBoundCredential: false,
                SVGAltGlyphDefElement: false,
                SVGAltGlyphElement: false,
                SVGAltGlyphItemElement: false,
                SVGAnimateColorElement: false,
                SVGAnimatedPathData: false,
                SVGAnimatedPoints: false,
                SVGColor: false,
                SVGColorProfileElement: false,
                SVGColorProfileRule: false,
                SVGCSSRule: false,
                SVGCursorElement: false,
                SVGDocument: false,
                SVGElementInstance: false,
                SVGElementInstanceList: false,
                SVGEvent: false,
                SVGExternalResourcesRequired: false,
                SVGFilterPrimitiveStandardAttributes: false,
                SVGFitToViewBox: false,
                SVGFontElement: false,
                SVGFontFaceElement: false,
                SVGFontFaceFormatElement: false,
                SVGFontFaceNameElement: false,
                SVGFontFaceSrcElement: false,
                SVGFontFaceUriElement: false,
                SVGGlyphElement: false,
                SVGGlyphRefElement: false,
                SVGHKernElement: false,
                SVGICCColor: false,
                SVGLangSpace: false,
                SVGLocatable: false,
                SVGMissingGlyphElement: false,
                SVGPaint: false,
                SVGPathSeg: false,
                SVGPathSegArcAbs: false,
                SVGPathSegArcRel: false,
                SVGPathSegClosePath: false,
                SVGPathSegCurvetoCubicAbs: false,
                SVGPathSegCurvetoCubicRel: false,
                SVGPathSegCurvetoCubicSmoothAbs: false,
                SVGPathSegCurvetoCubicSmoothRel: false,
                SVGPathSegCurvetoQuadraticAbs: false,
                SVGPathSegCurvetoQuadraticRel: false,
                SVGPathSegCurvetoQuadraticSmoothAbs: false,
                SVGPathSegCurvetoQuadraticSmoothRel: false,
                SVGPathSegLinetoAbs: false,
                SVGPathSegLinetoHorizontalAbs: false,
                SVGPathSegLinetoHorizontalRel: false,
                SVGPathSegLinetoRel: false,
                SVGPathSegLinetoVerticalAbs: false,
                SVGPathSegLinetoVerticalRel: false,
                SVGPathSegList: false,
                SVGPathSegMovetoAbs: false,
                SVGPathSegMovetoRel: false,
                SVGRenderingIntent: false,
                SVGStylable: false,
                SVGTests: false,
                SVGTransformable: false,
                SVGTRefElement: false,
                SVGURIReference: false,
                SVGViewSpec: false,
                SVGVKernElement: false,
                SVGZoomAndPan: false,
                SVGZoomEvent: false,
                TimeEvent: false,
                XDomainRequest: false,
                XMLHttpRequestProgressEvent: false,
                XPathException: false,
                XPathNamespace: false,
                XPathNSResolver: false
            },
            globals.browser
        )
    },
    node: {

        /*
         * For backward compatibility.
         * Remove those on the next major release.
         */
        globals: Object.assign(
            { arguments: false, GLOBAL: false, root: false },
            globals.node
        ),
        parserOptions: {
            ecmaFeatures: {
                globalReturn: true
            }
        }
    },
    commonjs: {
        globals: globals.commonjs,
        parserOptions: {
            ecmaFeatures: {
                globalReturn: true
            }
        }
    },
    "shared-node-browser": {
        globals: globals["shared-node-browser"]
    },
    worker: {
        globals: globals.worker
    },
    amd: {
        globals: globals.amd
    },
    mocha: {
        globals: globals.mocha
    },
    jasmine: {
        globals: globals.jasmine
    },
    jest: {

        /*
         * For backward compatibility.
         * Remove those on the next major release.
         */
        globals: Object.assign(
            { check: false, gen: false },
            globals.jest
        )
    },
    phantomjs: {
        globals: globals.phantomjs
    },
    jquery: {
        globals: globals.jquery
    },
    qunit: {
        globals: globals.qunit
    },
    prototypejs: {
        globals: globals.prototypejs
    },
    shelljs: {
        globals: globals.shelljs
    },
    meteor: {
        globals: globals.meteor
    },
    mongo: {
        globals: globals.mongo
    },
    protractor: {
        globals: globals.protractor
    },
    applescript: {
        globals: globals.applescript
    },
    nashorn: {
        globals: globals.nashorn
    },
    serviceworker: {
        globals: globals.serviceworker
    },
    atomtest: {
        globals: globals.atomtest
    },
    embertest: {
        globals: globals.embertest
    },
    webextensions: {
        globals: globals.webextensions
    },
    es6: {
        globals: globals.es2015,
        parserOptions: {
            ecmaVersion: 6
        }
    },
    greasemonkey: {
        globals: globals.greasemonkey
    }
};
<commit_msg>Breaking: remove deprecated browser/jest/node globals (fixes #10141) (#10210)<commit_after>/**
 * @fileoverview Defines environment settings and globals.
 * @author Elan Shanker
 */
"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const globals = require("globals");

//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------

module.exports = {
    builtin: {
        globals: globals.es5
    },
    browser: {
        globals: globals.browser
    },
    node: {
        globals: globals.node,
        parserOptions: {
            ecmaFeatures: {
                globalReturn: true
            }
        }
    },
    commonjs: {
        globals: globals.commonjs,
        parserOptions: {
            ecmaFeatures: {
                globalReturn: true
            }
        }
    },
    "shared-node-browser": {
        globals: globals["shared-node-browser"]
    },
    worker: {
        globals: globals.worker
    },
    amd: {
        globals: globals.amd
    },
    mocha: {
        globals: globals.mocha
    },
    jasmine: {
        globals: globals.jasmine
    },
    jest: {
        globals: globals.jest
    },
    phantomjs: {
        globals: globals.phantomjs
    },
    jquery: {
        globals: globals.jquery
    },
    qunit: {
        globals: globals.qunit
    },
    prototypejs: {
        globals: globals.prototypejs
    },
    shelljs: {
        globals: globals.shelljs
    },
    meteor: {
        globals: globals.meteor
    },
    mongo: {
        globals: globals.mongo
    },
    protractor: {
        globals: globals.protractor
    },
    applescript: {
        globals: globals.applescript
    },
    nashorn: {
        globals: globals.nashorn
    },
    serviceworker: {
        globals: globals.serviceworker
    },
    atomtest: {
        globals: globals.atomtest
    },
    embertest: {
        globals: globals.embertest
    },
    webextensions: {
        globals: globals.webextensions
    },
    es6: {
        globals: globals.es2015,
        parserOptions: {
            ecmaVersion: 6
        }
    },
    greasemonkey: {
        globals: globals.greasemonkey
    }
};
<|endoftext|>


<commit_before>(function(document, window, undefined) {
 'use strict';

/**
 * Module to graph live player data
 * Uses Flot.js to power the graphs
 */
window.Graphs = function(inputData) {
    var FUNCS = {
        "points": function(p) { return p.points; }
        , "vorp": function(p) { return p.vorp; }
        // TODO: derivative(points) ?
    }

    , playerEstimates = inputData
    ;

    // Flot hack - Makes the max value on an axis a label instead of the number
    function axisHack(name) {
        return function(val, axis) {
            return val < axis.max ? val.toFixed(2) : name;
        };
    };

    /**
     * Given a list of player objects, return a tuple for use by flot
     */
    function getPositionData(positionEstimates, type) {
        var players = []
        , dataFunc = FUNCS[type]
        ;
        $.each(positionEstimates, function(i, p) {
            players.push([i + 1, dataFunc(p)]);
        });
        return players;
    };

    function drawGraph(type) {
        var graphData = []
        ;
        $.each(playerEstimates, function(i, positionList) {
            var rawData = getPositionData(positionList, type);
            graphData.push({
                label:i
                , data:rawData
            });
        });
        $.plot("#pos_graph", graphData, {
            yaxis: { tickFormatter: axisHack(type) }
        });
    };

    function redrawActive() {
        var activeType = $(".graph button.active").data("type");
        drawGraph(activeType);
    };

    function attachListeners() {
        $(window).on(window.ff.UPDATE, redrawActive);
        $(".graph button").on("click", function() {
            drawGraph($(this).data("type"));
        });
    };

    attachListeners();
    redrawActive();
};

})(document, window);
<commit_msg>moved redraw to a 2sec timeout so the UI doesn't explode<commit_after>(function(document, window, undefined) {
 'use strict';

/**
 * Module to graph live player data
 * Uses Flot.js to power the graphs
 */
window.Graphs = function(inputData) {
    var FUNCS = {
        "points": function(p) { return p.points; }
        , "vorp": function(p) { return p.vorp; }
        // TODO: derivative(points) ?
    }

    , playerEstimates = inputData // reference to main bot data

    , nextRedraw = null // next scheduled redraw
    ;

    // Flot hack - Makes the max value on an axis a label instead of the number
    function axisHack(name) {
        return function(val, axis) {
            return val < axis.max ? val.toFixed(2) : name;
        };
    };

    /**
     * Given a list of player objects, return a tuple for use by flot
     */
    function getPositionData(positionEstimates, type) {
        var players = []
        , dataFunc = FUNCS[type]
        ;
        $.each(positionEstimates, function(i, p) {
            players.push([i + 1, dataFunc(p)]);
        });
        return players;
    };

    function drawGraph(type) {
        var graphData = []
        ;
        $.each(playerEstimates, function(i, positionList) {
            var rawData = getPositionData(positionList, type);
            graphData.push({
                label:i
                , data:rawData
            });
        });
        $.plot("#pos_graph", graphData, {
            yaxis: { tickFormatter: axisHack(type) }
        });
    };

    function redrawActive() {
        var activeType = $(".graph button.active").data("type");
        drawGraph(activeType);
    };

    function queueRedraw() {
        if (!nextRedraw) {
            nextRedraw = setTimeout(function() {
                redrawActive();
                nextRedraw = null;
            }, 2000);
        }
    }

    function attachListeners() {
        $(window).on(window.ff.UPDATE, queueRedraw);
        $(".graph button").on("click", function() {
            drawGraph($(this).data("type"));
        });
    };

    attachListeners();
    redrawActive();
};

})(document, window);
<|endoftext|>


<commit_before>knockoutDebugCallback([
    'src/namespace.js',
    'src/google-closure-compiler-utils.js',
    'src/version.js',
    'src/utils.js',
    'src/utils.domData.js',
    'src/utils.domNodeDisposal.js',
    'src/utils.domManipulation.js',
    'src/memoization.js',
    'src/subscribables/extenders.js',
    'src/subscribables/subscribable.js',
    'src/subscribables/dependencyDetection.js',
    'src/subscribables/observable.js',
    'src/subscribables/observableArray.js',
    'src/subscribables/dependentObservable.js',
    'src/subscribables/mappingHelpers.js',
    'src/binding/selectExtensions.js',
    'src/binding/expressionRewriting.js',
    'src/virtualElements.js',
    'src/binding/bindingProvider.js',
    'src/binding/bindingAttributeSyntax.js',
    'src/binding/defaultBindings/common.js',
    'src/binding/defaultBindings/attr.js',
    'src/binding/defaultBindings/checked.js',
    'src/binding/defaultBindings/css.js',
    'src/binding/defaultBindings/enableDisable.js',
    'src/binding/defaultBindings/event.js',
    'src/binding/defaultBindings/foreach.js',
    'src/binding/defaultBindings/hasfocus.js',
    'src/binding/defaultBindings/html.js',
    'src/binding/defaultBindings/if.js',
    'src/binding/defaultBindings/ifnot.js',
    'src/binding/defaultBindings/options.js',
    'src/binding/defaultBindings/selectedOptions.js',
    'src/binding/defaultBindings/style.js',
    'src/binding/defaultBindings/submit.js',
    'src/binding/defaultBindings/text.js',
    'src/binding/defaultBindings/uniqueName.js',
    'src/binding/defaultBindings/value.js',
    'src/binding/defaultBindings/visible.js',
    'src/binding/defaultBindings/with.js',
    // click depends on event - The order matters for specs, which includes each file individually
    'src/binding/defaultBindings/click.js',
    'src/templating/templateEngine.js',
    'src/templating/templateRewriting.js',
    'src/templating/templateSources.js',
    'src/templating/templating.js',
    'src/binding/editDetection/compareArrays.js',
    'src/binding/editDetection/arrayToDomNodeChildren.js',
    'src/templating/native/nativeTemplateEngine.js',
    'src/templating/jquery.tmpl/jqueryTmplTemplateEngine.js'
]);
<commit_msg>Remove the reference to the non-existent file<commit_after>knockoutDebugCallback([
    'src/namespace.js',
    'src/google-closure-compiler-utils.js',
    'src/version.js',
    'src/utils.js',
    'src/utils.domData.js',
    'src/utils.domNodeDisposal.js',
    'src/utils.domManipulation.js',
    'src/memoization.js',
    'src/subscribables/extenders.js',
    'src/subscribables/subscribable.js',
    'src/subscribables/dependencyDetection.js',
    'src/subscribables/observable.js',
    'src/subscribables/observableArray.js',
    'src/subscribables/dependentObservable.js',
    'src/subscribables/mappingHelpers.js',
    'src/binding/selectExtensions.js',
    'src/binding/expressionRewriting.js',
    'src/virtualElements.js',
    'src/binding/bindingProvider.js',
    'src/binding/bindingAttributeSyntax.js',
    'src/binding/defaultBindings/attr.js',
    'src/binding/defaultBindings/checked.js',
    'src/binding/defaultBindings/css.js',
    'src/binding/defaultBindings/enableDisable.js',
    'src/binding/defaultBindings/event.js',
    'src/binding/defaultBindings/foreach.js',
    'src/binding/defaultBindings/hasfocus.js',
    'src/binding/defaultBindings/html.js',
    'src/binding/defaultBindings/if.js',
    'src/binding/defaultBindings/ifnot.js',
    'src/binding/defaultBindings/options.js',
    'src/binding/defaultBindings/selectedOptions.js',
    'src/binding/defaultBindings/style.js',
    'src/binding/defaultBindings/submit.js',
    'src/binding/defaultBindings/text.js',
    'src/binding/defaultBindings/uniqueName.js',
    'src/binding/defaultBindings/value.js',
    'src/binding/defaultBindings/visible.js',
    'src/binding/defaultBindings/with.js',
    // click depends on event - The order matters for specs, which includes each file individually
    'src/binding/defaultBindings/click.js',
    'src/templating/templateEngine.js',
    'src/templating/templateRewriting.js',
    'src/templating/templateSources.js',
    'src/templating/templating.js',
    'src/binding/editDetection/compareArrays.js',
    'src/binding/editDetection/arrayToDomNodeChildren.js',
    'src/templating/native/nativeTemplateEngine.js',
    'src/templating/jquery.tmpl/jqueryTmplTemplateEngine.js'
]);
<|endoftext|>


<commit_before>import 'core-js/es6/map';
import 'core-js/es6/set';
import { AppRegistry } from 'react-native';
import { StackNavigator } from 'react-navigation';
import IndexPage from './pages/IndexPage';
import { UIFORM, UICONROL, UIVIEW } from './demoList';

const getOptions = title => ({
  title,
  headerStyle: {
    backgroundColor: '#12c287',
  },
  headerTintColor: 'white',
});

const scenes = {
  Index: {
    screen: IndexPage,
    navigationOptions: getOptions('Zarm UI - 众安科技移动端组件库'),
  },
};

[...UIFORM, ...UICONROL, ...UIVIEW].forEach((component) => {
  scenes[component.title] = {
    screen: component.module.default,
    navigationOptions: getOptions(component.title),
  };
});

const App = StackNavigator(scenes);

AppRegistry.registerComponent('zarm', () => App);

export default App;
<commit_msg>navbar title align center<commit_after>import 'core-js/es6/map';
import 'core-js/es6/set';
import React from 'react';
import { AppRegistry, View, Text } from 'react-native';
import { StackNavigator } from 'react-navigation';
import IndexPage from './pages/IndexPage';
import { UIFORM, UICONROL, UIVIEW } from './demoList';

const getOptions = title => ({
  headerTitle: (
    <View style={{ flex: 1 }}>
      <Text style={{ fontSize: 16, alignSelf: 'center', textAlign: 'center', color: '#fff' }}>{title}</Text>
    </View>
  ),
  headerStyle: {
    backgroundColor: '#12c287',
  },
  headerTintColor: 'white',
  headerRight: <View />,
});

const scenes = {
  Index: {
    screen: IndexPage,
    navigationOptions: {
      ...getOptions('Zarm UI'),
      headerLeft: <View />,
    },
  },
};

[...UIFORM, ...UICONROL, ...UIVIEW].forEach((component) => {
  scenes[component.title] = {
    screen: component.module.default,
    navigationOptions: getOptions(component.title),
  };
});

const App = StackNavigator(scenes);

AppRegistry.registerComponent('zarm', () => App);

export default App;
<|endoftext|>


<commit_before>/**
 * you should use vue-loader to pack .vue files for weex-vue-render.
 * you definitely should use compoilerModules to add $processStyle for weex-vue-render.
 */

var path = require('path');
var fs = require('fs-extra');
var webpack = require('webpack');

var entry = {};
var bannerExcludeFiles = [];
var webSrcDirectory = path.join(__dirname, '../examples/web-entry');

function getEntryFileContent (entryPath, vueFilePath) {
  const relativePath = path.relative(path.join(entryPath, '../'), vueFilePath);
  return 'var App = require(\'' + relativePath + '\')\n'
    + 'App.el = \'#root\'\n'
    + 'new Vue(App)\n'
}

function walk(dir) {
  dir = dir || '.';
  var directory = path.join(__dirname, '../examples', dir);
  var entryDirectory = path.join(webSrcDirectory, dir);
  fs.readdirSync(directory)
    .forEach(function(file) {
      var fullpath = path.join(directory, file);
      var stat = fs.statSync(fullpath);
      var extname = path.extname(fullpath);
      if (stat.isFile() && extname === '.vue') {
        var entryFile = path.join(entryDirectory, path.basename(file, extname) + '.js');
        fs.outputFileSync(entryFile, getEntryFileContent(entryFile, fullpath));
        var name = path.join('examples', 'build/vue-web', /*path.relative('vue', dir)*/dir, path.basename(file, extname));
        entry[name] = entryFile + '?entry=true';
      } else if (stat.isDirectory() && file !== 'build' && file !== 'include') {
        var subdir = path.join(dir, file);
        walk(subdir);
      }
    });
}

walk();

var banner = '// NOTE: for vue2.0 and platform:web only.\n'

var bannerPlugin = new webpack.BannerPlugin(banner, {
  raw: true,
  exclude: bannerExcludeFiles
})

module.exports = {
  entry: entry,
  output: {
    path: '.',
    filename: '[name].js'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        loaders: ['babel-loader'],
        exclude: /node_modules/
      }, {
        test: /\.vue(\?[^?]+)?$/,
        loaders: ['vue-loader']
      }
    ]
  },
  vue: {
    /**
     * important! should use postTransformNode to add $processStyle for
     * inline style prefixing.
     */
    compilerModules: [
      {
        postTransformNode: el => {
          el.staticStyle = `$processStyle(${el.staticStyle})`
          el.styleBinding = `$processStyle(${el.styleBinding})`
        }
      }
    ],
    autoprefixer: {
      browsers: ['last 7 versions']
    }
  },
  plugins: [bannerPlugin]
}
<commit_msg>* [html5] fix postcss config for vue-loader.<commit_after>/**
 * you should use vue-loader to pack .vue files for weex-vue-render.
 * you definitely should use compoilerModules to add $processStyle for weex-vue-render.
 */

var path = require('path');
var fs = require('fs-extra');
var webpack = require('webpack');

var entry = {};
var bannerExcludeFiles = [];
var webSrcDirectory = path.join(__dirname, '../examples/web-entry');

function getEntryFileContent (entryPath, vueFilePath) {
  const relativePath = path.relative(path.join(entryPath, '../'), vueFilePath);
  return 'var App = require(\'' + relativePath + '\')\n'
    + 'App.el = \'#root\'\n'
    + 'new Vue(App)\n'
}

function walk(dir) {
  dir = dir || '.';
  var directory = path.join(__dirname, '../examples', dir);
  var entryDirectory = path.join(webSrcDirectory, dir);
  fs.readdirSync(directory)
    .forEach(function(file) {
      var fullpath = path.join(directory, file);
      var stat = fs.statSync(fullpath);
      var extname = path.extname(fullpath);
      if (stat.isFile() && extname === '.vue') {
        var entryFile = path.join(entryDirectory, path.basename(file, extname) + '.js');
        fs.outputFileSync(entryFile, getEntryFileContent(entryFile, fullpath));
        var name = path.join('examples', 'build/vue-web', /*path.relative('vue', dir)*/dir, path.basename(file, extname));
        entry[name] = entryFile + '?entry=true';
      } else if (stat.isDirectory() && file !== 'build' && file !== 'include') {
        var subdir = path.join(dir, file);
        walk(subdir);
      }
    });
}

walk();

var banner = '// NOTE: for vue2.0 and platform:web only.\n'

var bannerPlugin = new webpack.BannerPlugin(banner, {
  raw: true,
  exclude: bannerExcludeFiles
})

module.exports = {
  entry: entry,
  output: {
    path: '.',
    filename: '[name].js'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        loaders: ['babel-loader'],
        exclude: /node_modules/
      }, {
        test: /\.vue(\?[^?]+)?$/,
        loaders: ['vue-loader']
      }
    ]
  },
  vue: {
    /**
     * important! should use postTransformNode to add $processStyle for
     * inline style prefixing.
     */
    compilerModules: [
      {
        postTransformNode: el => {
          el.staticStyle = `$processStyle(${el.staticStyle})`
          el.styleBinding = `$processStyle(${el.styleBinding})`
        }
      }
    ],
    postcss: [require('autoprefixer')()]
  },
  plugins: [bannerPlugin]
}
<|endoftext|>


<commit_before>/**
 * Blueprint API Configuration
 * (sails.config.blueprints)
 *
 * These settings are for the global configuration of blueprint routes and
 * request options (which impact the behavior of blueprint actions).
 *
 * You may also override any of these settings on a per-controller basis
 * by defining a '_config' key in your controller defintion, and assigning it
 * a configuration object with overrides for the settings in this file.
 * A lot of the configuration options below affect so-called "CRUD methods",
 * or your controllers' `find`, `create`, `update`, and `destroy` actions.
 *
 * It's important to realize that, even if you haven't defined these yourself, as long as
 * a model exists with the same name as the controller, Sails will respond with built-in CRUD
 * logic in the form of a JSON API, including support for sort, pagination, and filtering.
 *
 * For more information on the blueprint API, check out:
 * http://sailsjs.org/#/documentation/reference/blueprint-api
 *
 * For more information on the settings in this file, see:
 * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.blueprints.html
 *
 */

module.exports.blueprints = {

  /***************************************************************************
  *                                                                          *
  * Action routes speed up the backend development workflow by               *
  * eliminating the need to manually bind routes. When enabled, GET, POST,   *
  * PUT, and DELETE routes will be generated for every one of a controller's *
  * actions.                                                                 *
  *                                                                          *
  * If an `index` action exists, additional naked routes will be created for *
  * it. Finally, all `actions` blueprints support an optional path           *
  * parameter, `id`, for convenience.                                        *
  *                                                                          *
  * `actions` are enabled by default, and can be OK for production--         *
  * however, if you'd like to continue to use controller/action autorouting  *
  * in a production deployment, you must take great care not to              *
  * inadvertently expose unsafe/unintentional controller logic to GET        *
  * requests.                                                                *
  *                                                                          *
  ***************************************************************************/

  actions: false,

  /***************************************************************************
  *                                                                          *
  * RESTful routes (`sails.config.blueprints.rest`)                          *
  *                                                                          *
  * REST blueprints are the automatically generated routes Sails uses to     *
  * expose a conventional REST API on top of a controller's `find`,          *
  * `create`, `update`, and `destroy` actions.                               *
  *                                                                          *
  * For example, a BoatController with `rest` enabled generates the          *
  * following routes:                                                        *
  * :::::::::::::::::::::::::::::::::::::::::::::::::::::::                  *
  *  GET /boat/:id? -> BoatController.find                                   *
  *  POST /boat -> BoatController.create                                     *
  *  PUT /boat/:id -> BoatController.update                                  *
  *  DELETE /boat/:id -> BoatController.destroy                              *
  *                                                                          *
  * `rest` blueprint routes are enabled by default, and are suitable for use *
  * in a production scenario, as long you take standard security precautions *
  * (combine w/ policies, etc.)                                              *
  *                                                                          *
  ***************************************************************************/

  rest: true,

  /***************************************************************************
  *                                                                          *
  * Shortcut routes are simple helpers to provide access to a                *
  * controller's CRUD methods from your browser's URL bar. When enabled,     *
  * GET, POST, PUT, and DELETE routes will be generated for the              *
  * controller's`find`, `create`, `update`, and `destroy` actions.           *
  *                                                                          *
  * `shortcuts` are enabled by default, but should be disabled in            *
  * production.                                                              *
  *                                                                          *
  ***************************************************************************/

  // shortcuts: true,

  /***************************************************************************
  *                                                                          *
  * An optional mount path for all blueprint routes on a controller,         *
  * including `rest`, `actions`, and `shortcuts`. This allows you to take    *
  * advantage of blueprint routing, even if you need to namespace your API   *
  * methods.                                                                 *
  *                                                                          *
  * (NOTE: This only applies to blueprint autoroutes, not manual routes from *
  * `sails.config.routes`)                                                   *
  *                                                                          *
  ***************************************************************************/

  // prefix: '',

  /***************************************************************************
  *                                                                          *
  * Whether to pluralize controller names in blueprint routes.               *
  *                                                                          *
  * (NOTE: This only applies to blueprint autoroutes, not manual routes from *
  * `sails.config.routes`)                                                   *
  *                                                                          *
  * For example, REST blueprints for `FooController` with `pluralize`        *
  * enabled:                                                                 *
  * GET /foos/:id?                                                           *
  * POST /foos                                                               *
  * PUT /foos/:id?                                                           *
  * DELETE /foos/:id?                                                        *
  *                                                                          *
  ***************************************************************************/

  // pluralize: false,

  /***************************************************************************
  *                                                                          *
  * Whether the blueprint controllers should populate model fetches with     *
  * data from other models which are linked by associations                  *
  *                                                                          *
  * If you have a lot of data in one-to-many associations, leaving this on   *
  * may result in very heavy api calls                                       *
  *                                                                          *
  ***************************************************************************/

  // populate: true,

  /****************************************************************************
  *                                                                           *
  * Whether to run Model.watch() in the find and findOne blueprint actions.   *
  * Can be overridden on a per-model basis.                                   *
  *                                                                           *
  ****************************************************************************/

  // autoWatch: true,

  /****************************************************************************
  *                                                                           *
  * The default number of records to show in the response from a "find"       *
  * action. Doubles as the default size of populated arrays if populate is    *
  * true.                                                                     *
  *                                                                           *
  ****************************************************************************/

  // defaultLimit: 30

};
<commit_msg>Security #5<commit_after>/**
 * Blueprint API Configuration
 * (sails.config.blueprints)
 *
 * These settings are for the global configuration of blueprint routes and
 * request options (which impact the behavior of blueprint actions).
 *
 * You may also override any of these settings on a per-controller basis
 * by defining a '_config' key in your controller defintion, and assigning it
 * a configuration object with overrides for the settings in this file.
 * A lot of the configuration options below affect so-called "CRUD methods",
 * or your controllers' `find`, `create`, `update`, and `destroy` actions.
 *
 * It's important to realize that, even if you haven't defined these yourself, as long as
 * a model exists with the same name as the controller, Sails will respond with built-in CRUD
 * logic in the form of a JSON API, including support for sort, pagination, and filtering.
 *
 * For more information on the blueprint API, check out:
 * http://sailsjs.org/#/documentation/reference/blueprint-api
 *
 * For more information on the settings in this file, see:
 * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.blueprints.html
 *
 */

module.exports.blueprints = {

  /***************************************************************************
  *                                                                          *
  * Action routes speed up the backend development workflow by               *
  * eliminating the need to manually bind routes. When enabled, GET, POST,   *
  * PUT, and DELETE routes will be generated for every one of a controller's *
  * actions.                                                                 *
  *                                                                          *
  * If an `index` action exists, additional naked routes will be created for *
  * it. Finally, all `actions` blueprints support an optional path           *
  * parameter, `id`, for convenience.                                        *
  *                                                                          *
  * `actions` are enabled by default, and can be OK for production--         *
  * however, if you'd like to continue to use controller/action autorouting  *
  * in a production deployment, you must take great care not to              *
  * inadvertently expose unsafe/unintentional controller logic to GET        *
  * requests.                                                                *
  *                                                                          *
  ***************************************************************************/

  actions: false,

  /***************************************************************************
  *                                                                          *
  * RESTful routes (`sails.config.blueprints.rest`)                          *
  *                                                                          *
  * REST blueprints are the automatically generated routes Sails uses to     *
  * expose a conventional REST API on top of a controller's `find`,          *
  * `create`, `update`, and `destroy` actions.                               *
  *                                                                          *
  * For example, a BoatController with `rest` enabled generates the          *
  * following routes:                                                        *
  * :::::::::::::::::::::::::::::::::::::::::::::::::::::::                  *
  *  GET /boat/:id? -> BoatController.find                                   *
  *  POST /boat -> BoatController.create                                     *
  *  PUT /boat/:id -> BoatController.update                                  *
  *  DELETE /boat/:id -> BoatController.destroy                              *
  *                                                                          *
  * `rest` blueprint routes are enabled by default, and are suitable for use *
  * in a production scenario, as long you take standard security precautions *
  * (combine w/ policies, etc.)                                              *
  *                                                                          *
  ***************************************************************************/

  rest: true,

  /***************************************************************************
  *                                                                          *
  * Shortcut routes are simple helpers to provide access to a                *
  * controller's CRUD methods from your browser's URL bar. When enabled,     *
  * GET, POST, PUT, and DELETE routes will be generated for the              *
  * controller's`find`, `create`, `update`, and `destroy` actions.           *
  *                                                                          *
  * `shortcuts` are enabled by default, but should be disabled in            *
  * production.                                                              *
  *                                                                          *
  ***************************************************************************/

  shortcuts: false,

  /***************************************************************************
  *                                                                          *
  * An optional mount path for all blueprint routes on a controller,         *
  * including `rest`, `actions`, and `shortcuts`. This allows you to take    *
  * advantage of blueprint routing, even if you need to namespace your API   *
  * methods.                                                                 *
  *                                                                          *
  * (NOTE: This only applies to blueprint autoroutes, not manual routes from *
  * `sails.config.routes`)                                                   *
  *                                                                          *
  ***************************************************************************/

  // prefix: '',

  /***************************************************************************
  *                                                                          *
  * Whether to pluralize controller names in blueprint routes.               *
  *                                                                          *
  * (NOTE: This only applies to blueprint autoroutes, not manual routes from *
  * `sails.config.routes`)                                                   *
  *                                                                          *
  * For example, REST blueprints for `FooController` with `pluralize`        *
  * enabled:                                                                 *
  * GET /foos/:id?                                                           *
  * POST /foos                                                               *
  * PUT /foos/:id?                                                           *
  * DELETE /foos/:id?                                                        *
  *                                                                          *
  ***************************************************************************/

  pluralize: false,

  /***************************************************************************
  *                                                                          *
  * Whether the blueprint controllers should populate model fetches with     *
  * data from other models which are linked by associations                  *
  *                                                                          *
  * If you have a lot of data in one-to-many associations, leaving this on   *
  * may result in very heavy api calls                                       *
  *                                                                          *
  ***************************************************************************/

  // populate: true,

  /****************************************************************************
  *                                                                           *
  * Whether to run Model.watch() in the find and findOne blueprint actions.   *
  * Can be overridden on a per-model basis.                                   *
  *                                                                           *
  ****************************************************************************/

  // autoWatch: true,

  /****************************************************************************
  *                                                                           *
  * The default number of records to show in the response from a "find"       *
  * action. Doubles as the default size of populated arrays if populate is    *
  * true.                                                                     *
  *                                                                           *
  ****************************************************************************/

  // defaultLimit: 30

};
<|endoftext|>