<commit_before>var dtar = require('deterministic-tar')
var zlib = require('zlib')
var path = require('path')
var concat = require('concat-stream')

//unpack and repack a stream so that it always hashes the same,
//by it's content, not it's timestamps.

module.exports = function (stream, cb) {

  var offset = new Date().getTimezoneOffset() * -1
  var THE_BEGINNING_OF_TIME = new Date(offset)

  var buffer = []
  var ended = false

  function errback (err) {
    if(ended) return
    cb(ended = err)
  }

  stream
    .pipe(zlib.createGunzip())
    .on('error', errback)
    .pipe(dtar())
    .on('error', errback)
    .pipe(zlib.createGzip())
    .pipe(concat(function (data) {
      if(ended) return
      ended = true
      cb(null, data)
    }))
}
<commit_msg>fix github dirs when downloading<commit_after>var dtar = require('deterministic-tar')
var zlib = require('zlib')
var path = require('path')
var concat = require('concat-stream')

//unpack and repack a stream so that it always hashes the same,
//by it's content, not it's timestamps.

module.exports = function (stream, cb) {

  var offset = new Date().getTimezoneOffset() * -1
  var THE_BEGINNING_OF_TIME = new Date(offset)

  var buffer = []
  var ended = false

  function errback (err) {
    if(ended) return
    cb(ended = err)
  }

  stream
    .pipe(zlib.createGunzip())
    .on('error', errback)
    .pipe(dtar(function (header) {
      var i = header.name.indexOf('/')
      var dir = header.name.substring(0, i)
      if(dir !== 'package')
        header.name = 'package'+ header.name.substring(i)
      return header
    }))
    .on('error', errback)
    .pipe(zlib.createGzip())
    .pipe(concat(function (data) {
      if(ended) return
      ended = true
      cb(null, data)
    }))
}
<|endoftext|>


<commit_before>import test from 'ava';
import mockFs from 'mock-fs';
import findPatterns from '../source/find-patterns';

const mocks = {
	unrelated: {
		components: {
			'unrelated.js': 'blah'
		}
	}
};

test('when calling find-patterns with no arguments', t => {
	const actual = findPatterns();
	t.throws(actual, Error, 'it should throw a Error');
});

test('when calling find-patterns with a non-existing path', t => {
	const actual = findPatterns('./something/very/unlikely');
	t.throws(actual, RangeError, 'it should throw a RangeError');
});

test('when no patterns are found in given directory', async t => {
	mockFs(mocks.unrelated);
	const actual = await findPatterns('./components');
	t.same(actual, [], 'it should return an empty array');
	mockFs.restore();
});

test('when calling find-patterns with a file path', t => {
	mockFs(mocks.unrelated);
	const actual = findPatterns('./components/unrelated.js');
	t.throws(actual, RangeError, 'it should throw a RangeError');
	mockFs.restore();
});
<commit_msg>refactor(tests): use test.after() hook for fs mocks<commit_after>import test from 'ava';
import mockFs from 'mock-fs';
import findPatterns from '../source/find-patterns';

const mocks = {
	unrelated: {
		'components/unrelated.js': 'blah'
		}
	}
};

test.after(() => {
	mockFs.restore();
});

test('when calling find-patterns with no arguments', t => {
	const actual = findPatterns();
	t.throws(actual, Error, 'it should throw a Error');
});

test('when calling find-patterns with a non-existing path', t => {
	const actual = findPatterns('./something/very/unlikely');
	t.throws(actual, RangeError, 'it should throw a RangeError');
});

test('when no patterns are found in given directory', async t => {
	mockFs(mocks.unrelated);
	const actual = await findPatterns('./components');
	t.same(actual, [], 'it should return an empty array');
});

test('when calling find-patterns with a file path', t => {
	mockFs(mocks.unrelated);
	const actual = findPatterns('./components/unrelated.js');
	t.throws(actual, RangeError, 'it should throw a RangeError');
});
<|endoftext|>


<commit_before>/*
 *     Copyright (c) 2012-2014 CoNWeT Lab., Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU Affero General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Wirecloud is distributed in the hope that it will be useful, but WITHOUT
 *     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 *     License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/*global CatalogueSearchView, gettext, interpolate, LayoutManagerFactory, Wirecloud, StyledElements*/

(function () {

    "use strict";

    var CatalogueView = function CatalogueView(id, options) {
        var resource_extra_context;

        options.class = 'catalogue';
        StyledElements.Alternative.call(this, id, options);

        Object.defineProperty(this, 'desc', {value: options.marketplace_desc});
        if (this.desc.user != null) {
            this.market_id = this.desc.user + '/' + this.desc.name;
        } else {
            this.market_id = this.desc.name;
        }
        if (this.desc.name === 'local') {
            this.catalogue = Wirecloud.LocalCatalogue;
        } else {
            this.catalogue = new Wirecloud.WirecloudCatalogue(options.marketplace_desc);
        }
        this.alternatives = new StyledElements.StyledAlternatives();
        this.appendChild(this.alternatives);

        if (this.catalogue !== Wirecloud.LocalCatalogue) {
            resource_extra_context = {
                'mainbutton': function (options, context, resource) {
                    var button, local_catalogue_view;

                    local_catalogue_view = LayoutManagerFactory.getInstance().viewsByName.myresources;
                    if (Wirecloud.LocalCatalogue.resourceExists(resource)) {
                        button = new StyledElements.StyledButton({
                            'class': 'btn-danger',
                            'text': gettext('Uninstall')
                        });
                        button.addEventListener('click', local_catalogue_view.createUserCommand('uninstall', resource, this.catalogue));
                    } else {
                        button = new StyledElements.StyledButton({
                            'class': 'btn-success',
                            'text': gettext('Install')
                        });

                        button.addEventListener('click', local_catalogue_view.createUserCommand('install', resource, this.catalogue));
                    }
                    button.addClassName('mainbutton');
                    return button;
                }.bind(this)
            };
        }

        this.viewsByName = {
            'initial': this.alternatives.createAlternative(),
            'search': this.alternatives.createAlternative({alternative_constructor: CatalogueSearchView, containerOptions: {catalogue: this, resource_painter: Wirecloud.ui.ResourcePainter, resource_extra_context: resource_extra_context}}),
            'details': this.alternatives.createAlternative({alternative_constructor: Wirecloud.ui.WirecloudCatalogue.ResourceDetailsView, containerOptions: {catalogue: this}})
        };
        this.viewsByName.search.init();

        this.alternatives.addEventListener('postTransition', function (alternatives, out_alternative) {
            var new_status = options.catalogue.buildStateData();

            if (out_alternative === this.viewsByName.initial) {
                Wirecloud.HistoryManager.replaceState(new_status);
            } else {
                Wirecloud.HistoryManager.pushState(new_status);
            }
        }.bind(this));

        this.addEventListener('show', function () {
            if (this.alternatives.getCurrentAlternative() === this.viewsByName.initial) {
                this.changeCurrentView('search');
            }
            this.refresh_if_needed();
        }.bind(this));
    };
    CatalogueView.prototype = new StyledElements.Alternative();

    CatalogueView.prototype.getLabel = function getLabel() {
        return this.catalogue.name;
    };

    CatalogueView.prototype._onShow = function _onShow() {
    };

    CatalogueView.prototype.onHistoryChange = function onHistoryChange(state) {
        this.changeCurrentView(state.subview);
    };

    CatalogueView.prototype.goUp = function goUp() {
        if (this.alternatives.getCurrentAlternative() === this.viewsByName.search) {
            return false;
        }
        this.changeCurrentView('search');
        return true;
    };

    CatalogueView.prototype.search = function search(onSuccess, onError, options) {
        return this.catalogue.search(onSuccess, onError, options);
    };

    CatalogueView.prototype.getPublishEndpoints = function getPublishEndpoints() {
        return null;
    };

    CatalogueView.prototype.changeCurrentView = function changeCurrentView(view_name) {
        if (!(view_name in this.viewsByName)) {
            throw new TypeError();
        }

        this.alternatives.showAlternative(this.viewsByName[view_name]);
    };

    CatalogueView.prototype.home = function home() {
        this.changeCurrentView('search');
    };

    CatalogueView.prototype.createUserCommand = function createUserCommand(command) {
        return this.ui_commands[command].apply(this, Array.prototype.slice.call(arguments, 1));
    };

    CatalogueView.prototype.ui_commands = {};

    CatalogueView.prototype.ui_commands.install = function install(resource, catalogue_source) {
        return function () {
            var layoutManager;

            layoutManager = LayoutManagerFactory.getInstance();
            layoutManager._startComplexTask(gettext("Importing resource into local repository"), 3);
            layoutManager.logSubTask(gettext('Uploading resource'));

            this.catalogue.addResourceFromURL(resource.description_url, {
                packaged: resource.packaged,
                onSuccess: function () {
                    LayoutManagerFactory.getInstance().logSubTask(gettext('Resource installed successfully'));
                    LayoutManagerFactory.getInstance().logStep('');

                    this.refresh_search_results();

                    catalogue_source.home();
                    catalogue_source.refresh_search_results();
                }.bind(this),
                onFailure: function (msg) {
                    (new Wirecloud.ui.MessageWindowMenu(msg, Wirecloud.constants.LOGGING.ERROR_MSG)).show();
                    Wirecloud.GlobalLogManager.log(msg);
                },
                onComplete: function () {
                    LayoutManagerFactory.getInstance()._notifyPlatformReady();
                }
            });
        }.bind(this);
    };

    CatalogueView.prototype.ui_commands.uninstall = function uninstall(resource, catalogue_source) {
        return function () {
            var layoutManager;

            layoutManager = LayoutManagerFactory.getInstance();
            layoutManager._startComplexTask(gettext("Uninstalling resource"), 3);
            layoutManager.logSubTask(gettext('Uninstalling resource'));

            this.catalogue.uninstallResource(resource, {
                onSuccess: function () {
                    LayoutManagerFactory.getInstance().logSubTask(gettext('Resource uninstalled successfully'));
                    LayoutManagerFactory.getInstance().logStep('');

                    this.refresh_search_results();

                    if (catalogue_source != null) {
                        catalogue_source.home();
                        catalogue_source.refresh_search_results();
                    }
                }.bind(this),
                onFailure: function (msg) {
                    (new Wirecloud.ui.MessageWindowMenu(msg, Wirecloud.constants.LOGGING.ERROR_MSG)).show();
                    Wirecloud.GlobalLogManager.log(msg);
                },
                onComplete: function () {
                    LayoutManagerFactory.getInstance()._notifyPlatformReady();
                }
            });
        }.bind(this);
    };

    CatalogueView.prototype.ui_commands.showDetails = function showDetails(resource) {
        return function (e) {
            var onSuccess = function (resource_details) {
                this.viewsByName.details.paint(resource_details);
                this.alternatives.showAlternative(this.viewsByName.details);
                this.viewsByName.details.repaint();
            };

            if (resource instanceof Wirecloud.WirecloudCatalogue.ResourceDetails) {
                onSuccess.call(this, resource);
            } else {
                this.catalogue.getResourceDetails(resource.vendor, resource.name, {
                    onSuccess: onSuccess.bind(this)
                });
            }
        }.bind(this);
    };

    CatalogueView.prototype.ui_commands.delete = function (resource) {
        var success_callback, error_callback, doRequest, msg, context;

        success_callback = function (response) {
            LayoutManagerFactory.getInstance()._notifyPlatformReady();
            this.home();
            this.refresh_search_results();
        }.bind(this);

        error_callback = function (msg) {
            LayoutManagerFactory.getInstance()._notifyPlatformReady();
            (new Wirecloud.ui.MessageWindowMenu(msg, Wirecloud.constants.LOGGING.ERROR_MSG)).show();
        };

        doRequest = function () {
            var layoutManager;

            layoutManager = LayoutManagerFactory.getInstance();
            layoutManager._startComplexTask(gettext("Deleting widget resource from catalogue"), 3);
            layoutManager.logSubTask(gettext('Requesting server'));

            this.catalogue.deleteResource(resource, success_callback, error_callback);
        };

        // First ask the user
        msg = gettext('Do you really want to remove the "%(name)s" (vendor: "%(vendor)s", version: "%(version)s") widget?');
        context = {
            vendor: resource.vendor,
            name: resource.name,
            version: resource.version.text
        };

        msg = interpolate(msg, context, true);
        return function () {
            var dialog = new Wirecloud.ui.AlertWindowMenu();
            dialog.setMsg(msg);
            dialog.setHandler(doRequest.bind(this));
            dialog.show();
        }.bind(this);
    };

    CatalogueView.prototype.refresh_if_needed = function refresh_if_needed() {
        if (this.alternatives.getCurrentAlternative() === this.viewsByName.search) {
            this.viewsByName.search.refresh_if_needed();
        }
    };

    CatalogueView.prototype.refresh_search_results = function () {
        this.viewsByName.search.source.refresh();
    };

    window.CatalogueView = CatalogueView;
})();
<commit_msg>Remove unused code<commit_after>/*
 *     Copyright (c) 2012-2014 CoNWeT Lab., Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU Affero General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Wirecloud is distributed in the hope that it will be useful, but WITHOUT
 *     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 *     License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/*global CatalogueSearchView, gettext, interpolate, LayoutManagerFactory, Wirecloud, StyledElements*/

(function () {

    "use strict";

    var CatalogueView = function CatalogueView(id, options) {
        var resource_extra_context;

        options.class = 'catalogue';
        StyledElements.Alternative.call(this, id, options);

        Object.defineProperty(this, 'desc', {value: options.marketplace_desc});
        if (this.desc.user != null) {
            this.market_id = this.desc.user + '/' + this.desc.name;
        } else {
            this.market_id = this.desc.name;
        }
        this.catalogue = new Wirecloud.WirecloudCatalogue(options.marketplace_desc);
        this.alternatives = new StyledElements.StyledAlternatives();
        this.appendChild(this.alternatives);

        resource_extra_context = {
            'mainbutton': function (options, context, resource) {
                var button, local_catalogue_view;

                local_catalogue_view = LayoutManagerFactory.getInstance().viewsByName.myresources;
                if (Wirecloud.LocalCatalogue.resourceExists(resource)) {
                    button = new StyledElements.StyledButton({
                        'class': 'btn-danger',
                        'text': gettext('Uninstall')
                    });
                    button.addEventListener('click', local_catalogue_view.createUserCommand('uninstall', resource, this.catalogue));
                } else {
                    button = new StyledElements.StyledButton({
                        'class': 'btn-success',
                        'text': gettext('Install')
                    });

                    button.addEventListener('click', local_catalogue_view.createUserCommand('install', resource, this.catalogue));
                }
                button.addClassName('mainbutton');
                return button;
            }.bind(this)
        };

        this.viewsByName = {
            'initial': this.alternatives.createAlternative(),
            'search': this.alternatives.createAlternative({alternative_constructor: CatalogueSearchView, containerOptions: {catalogue: this, resource_painter: Wirecloud.ui.ResourcePainter, resource_extra_context: resource_extra_context}}),
            'details': this.alternatives.createAlternative({alternative_constructor: Wirecloud.ui.WirecloudCatalogue.ResourceDetailsView, containerOptions: {catalogue: this}})
        };
        this.viewsByName.search.init();

        this.alternatives.addEventListener('postTransition', function (alternatives, out_alternative) {
            var new_status = options.catalogue.buildStateData();

            if (out_alternative === this.viewsByName.initial) {
                Wirecloud.HistoryManager.replaceState(new_status);
            } else {
                Wirecloud.HistoryManager.pushState(new_status);
            }
        }.bind(this));

        this.addEventListener('show', function () {
            if (this.alternatives.getCurrentAlternative() === this.viewsByName.initial) {
                this.changeCurrentView('search');
            }
            this.refresh_if_needed();
        }.bind(this));
    };
    CatalogueView.prototype = new StyledElements.Alternative();

    CatalogueView.prototype.getLabel = function getLabel() {
        return this.catalogue.name;
    };

    CatalogueView.prototype._onShow = function _onShow() {
    };

    CatalogueView.prototype.onHistoryChange = function onHistoryChange(state) {
        this.changeCurrentView(state.subview);
    };

    CatalogueView.prototype.goUp = function goUp() {
        if (this.alternatives.getCurrentAlternative() === this.viewsByName.search) {
            return false;
        }
        this.changeCurrentView('search');
        return true;
    };

    CatalogueView.prototype.search = function search(onSuccess, onError, options) {
        return this.catalogue.search(onSuccess, onError, options);
    };

    CatalogueView.prototype.getPublishEndpoints = function getPublishEndpoints() {
        return null;
    };

    CatalogueView.prototype.changeCurrentView = function changeCurrentView(view_name) {
        if (!(view_name in this.viewsByName)) {
            throw new TypeError();
        }

        this.alternatives.showAlternative(this.viewsByName[view_name]);
    };

    CatalogueView.prototype.home = function home() {
        this.changeCurrentView('search');
    };

    CatalogueView.prototype.createUserCommand = function createUserCommand(command) {
        return this.ui_commands[command].apply(this, Array.prototype.slice.call(arguments, 1));
    };

    CatalogueView.prototype.ui_commands = {};

    CatalogueView.prototype.ui_commands.install = function install(resource, catalogue_source) {
        return function () {
            var layoutManager;

            layoutManager = LayoutManagerFactory.getInstance();
            layoutManager._startComplexTask(gettext("Importing resource into local repository"), 3);
            layoutManager.logSubTask(gettext('Uploading resource'));

            this.catalogue.addResourceFromURL(resource.description_url, {
                packaged: resource.packaged,
                onSuccess: function () {
                    LayoutManagerFactory.getInstance().logSubTask(gettext('Resource installed successfully'));
                    LayoutManagerFactory.getInstance().logStep('');

                    this.refresh_search_results();

                    catalogue_source.home();
                    catalogue_source.refresh_search_results();
                }.bind(this),
                onFailure: function (msg) {
                    (new Wirecloud.ui.MessageWindowMenu(msg, Wirecloud.constants.LOGGING.ERROR_MSG)).show();
                    Wirecloud.GlobalLogManager.log(msg);
                },
                onComplete: function () {
                    LayoutManagerFactory.getInstance()._notifyPlatformReady();
                }
            });
        }.bind(this);
    };

    CatalogueView.prototype.ui_commands.uninstall = function uninstall(resource, catalogue_source) {
        return function () {
            var layoutManager;

            layoutManager = LayoutManagerFactory.getInstance();
            layoutManager._startComplexTask(gettext("Uninstalling resource"), 3);
            layoutManager.logSubTask(gettext('Uninstalling resource'));

            this.catalogue.uninstallResource(resource, {
                onSuccess: function () {
                    LayoutManagerFactory.getInstance().logSubTask(gettext('Resource uninstalled successfully'));
                    LayoutManagerFactory.getInstance().logStep('');

                    this.refresh_search_results();

                    if (catalogue_source != null) {
                        catalogue_source.home();
                        catalogue_source.refresh_search_results();
                    }
                }.bind(this),
                onFailure: function (msg) {
                    (new Wirecloud.ui.MessageWindowMenu(msg, Wirecloud.constants.LOGGING.ERROR_MSG)).show();
                    Wirecloud.GlobalLogManager.log(msg);
                },
                onComplete: function () {
                    LayoutManagerFactory.getInstance()._notifyPlatformReady();
                }
            });
        }.bind(this);
    };

    CatalogueView.prototype.ui_commands.showDetails = function showDetails(resource) {
        return function (e) {
            var onSuccess = function (resource_details) {
                this.viewsByName.details.paint(resource_details);
                this.alternatives.showAlternative(this.viewsByName.details);
                this.viewsByName.details.repaint();
            };

            if (resource instanceof Wirecloud.WirecloudCatalogue.ResourceDetails) {
                onSuccess.call(this, resource);
            } else {
                this.catalogue.getResourceDetails(resource.vendor, resource.name, {
                    onSuccess: onSuccess.bind(this)
                });
            }
        }.bind(this);
    };

    CatalogueView.prototype.ui_commands.delete = function (resource) {
        var success_callback, error_callback, doRequest, msg, context;

        success_callback = function (response) {
            LayoutManagerFactory.getInstance()._notifyPlatformReady();
            this.home();
            this.refresh_search_results();
        }.bind(this);

        error_callback = function (msg) {
            LayoutManagerFactory.getInstance()._notifyPlatformReady();
            (new Wirecloud.ui.MessageWindowMenu(msg, Wirecloud.constants.LOGGING.ERROR_MSG)).show();
        };

        doRequest = function () {
            var layoutManager;

            layoutManager = LayoutManagerFactory.getInstance();
            layoutManager._startComplexTask(gettext("Deleting widget resource from catalogue"), 3);
            layoutManager.logSubTask(gettext('Requesting server'));

            this.catalogue.deleteResource(resource, success_callback, error_callback);
        };

        // First ask the user
        msg = gettext('Do you really want to remove the "%(name)s" (vendor: "%(vendor)s", version: "%(version)s") widget?');
        context = {
            vendor: resource.vendor,
            name: resource.name,
            version: resource.version.text
        };

        msg = interpolate(msg, context, true);
        return function () {
            var dialog = new Wirecloud.ui.AlertWindowMenu();
            dialog.setMsg(msg);
            dialog.setHandler(doRequest.bind(this));
            dialog.show();
        }.bind(this);
    };

    CatalogueView.prototype.refresh_if_needed = function refresh_if_needed() {
        if (this.alternatives.getCurrentAlternative() === this.viewsByName.search) {
            this.viewsByName.search.refresh_if_needed();
        }
    };

    CatalogueView.prototype.refresh_search_results = function () {
        this.viewsByName.search.source.refresh();
    };

    window.CatalogueView = CatalogueView;
})();
<|endoftext|>


<commit_before>import { transform, getSubTreeOf } from './kanaMappingUtils';
import isKatakana from './isKatakana';
import katakanaToHiragana from './utils/katakanaToHiragana';

export const methods = Object.freeze({
  HEPBURN: 'hepburn',
});

let kanaToHepburnMap = null;

function createKanaToHepburnMap() {
  const romajiTree = transform({
    あ: 'a',
    い: 'i',
    う: 'u',
    え: 'e',
    お: 'o',
    か: 'ka',
    き: 'ki',
    く: 'ku',
    け: 'ke',
    こ: 'ko',
    さ: 'sa',
    し: 'shi',
    す: 'su',
    せ: 'se',
    そ: 'so',
    た: 'ta',
    ち: 'chi',
    つ: 'tsu',
    て: 'te',
    と: 'to',
    な: 'na',
    に: 'ni',
    ぬ: 'nu',
    ね: 'ne',
    の: 'no',
    は: 'ha',
    ひ: 'hi',
    ふ: 'fu',
    へ: 'he',
    ほ: 'ho',
    ま: 'ma',
    み: 'mi',
    む: 'mu',
    め: 'me',
    も: 'mo',
    や: 'ya',
    ゆ: 'yu',
    よ: 'yo',
    ら: 'ra',
    り: 'ri',
    る: 'ru',
    れ: 're',
    ろ: 'ro',
    わ: 'wa',
    ゐ: 'wi',
    ゑ: 'we',
    を: 'wo',
    が: 'ga',
    ぎ: 'gi',
    ぐ: 'gu',
    げ: 'ge',
    ご: 'go',
    ざ: 'za',
    じ: 'ji',
    ず: 'zu',
    ぜ: 'ze',
    ぞ: 'zo',
    だ: 'da',
    ぢ: 'ji',
    づ: 'zu',
    で: 'de',
    ど: 'do',
    ば: 'ba',
    び: 'bi',
    ぶ: 'bu',
    べ: 'be',
    ぼ: 'bo',
    ぱ: 'pa',
    ぴ: 'pi',
    ぷ: 'pu',
    ぺ: 'pe',
    ぽ: 'po',
    ゔぁ: 'va',
    ゔぃ: 'vi',
    ゔ: 'vu',
    ゔぇ: 've',
    ゔぉ: 'vo',
    ん: 'n',
  });

  const subtreeOf = (string) => getSubTreeOf(romajiTree, string);

  const specialSymbols = {
    '。': '.',
    '、': ',',
    '：': ':',
    '・': '/',
    '！': '!',
    '？': '?',
    '〜': '~',
    'ー': '-',
    '「': '‘',
    '」': '’',
    '『': '“',
    '』': '”',
    '［': '[',
    '］': ']',
    '（': '(',
    '）': ')',
    '｛': '{',
    '｝': '}',
    '　': ' ',
  };

  for (const [jsymbol, symbol] of Object.entries(specialSymbols)) {
    subtreeOf(jsymbol)[''] = symbol;
  }

  const smallY = { ゃ: 'ya', ゅ: 'yu', ょ: 'yo' };
  const smallYExtra = { ぃ: 'yi', ぇ: 'ye' };
  const smallaiueo = { ぁ: 'a', ぃ: 'i', ぅ: 'u', ぇ: 'e', ぉ: 'o' };

  for (const [rom, kan] of Object.entries(smallY).concat(Object.entries(smallaiueo))) {
    subtreeOf(rom)[''] = kan;
  }

  const yoonKana = ['き', 'に', 'ひ', 'み', 'り', 'ぎ', 'び', 'ぴ', 'ゔ', 'く', 'ふ'];
  // きゃ -> kya
  for (const kana of yoonKana) {
    const fistRomajiLetter = subtreeOf(kana)[''][0];
    for (const [yKan, yRom] of Object.entries(smallY)) {
      subtreeOf(kana + yKan)[''] = fistRomajiLetter + yRom;
    }
    // きぃ -> kyi
    for (const [yKan, yRom] of Object.entries(smallYExtra)) {
      subtreeOf(kana + yKan)[''] = fistRomajiLetter + yRom;
    }
  }
  const yoonExceptions = { し: 'sh', ち: 'ch', じ: 'j', ぢ: 'j' };
  for (const [kana, rom] of Object.entries(yoonExceptions)) {
    // じゃ -> ja
    for (const [yKan, yRom] of Object.entries(smallY)) {
      subtreeOf(kana + yKan)[''] = rom + yRom[1];
    }
    // じぃ -> jyi, じぇ -> je
    subtreeOf(`${kana}ぃ`)[''] = `${rom}yi`;
    subtreeOf(`${kana}ぇ`)[''] = `${rom}e`;
  }

  // going with the intuitive (yet incorrect) solution where っや -> yya and っぃ -> ii
  // in other words, just assume the sokuon could have been applied to anything

  const sokuonWhitelist = {
    b: 'b',
    c: 't',
    d: 'd',
    f: 'f',
    g: 'g',
    h: 'h',
    j: 'j',
    k: 'k',
    m: 'm',
    p: 'p',
    q: 'q',
    r: 'r',
    s: 's',
    t: 't',
    v: 'v',
    w: 'w',
    x: 'x',
    z: 'z',
  };

  function resolveTsu(tree) {
    const result = {};
    for (const [key, value] of Object.entries(tree)) {
      if (!key) {  // we have reached the bottom of this branch
        const consonant = value.charAt(0);
        result[key] = consonant in sokuonWhitelist?
          sokuonWhitelist[consonant] + value:
          value;
      } else {  // more subtrees
        result[key] = resolveTsu(value);
      }
    }
    return result;
  }

  romajiTree['っ'] = resolveTsu(romajiTree);

  const smallLetters = {
    っ: '',
    ゎ: 'wa',
    ゕ: 'ka',
    ゖ: 'ka',  // because katakana is converted to hiragana before calling this function
    ゃ: 'ya',
    ゅ: 'yu',
    ょ: 'yo',
    ぁ: 'a',
    ぃ: 'i',
    ぅ: 'u',
    ぇ: 'e',
    ぉ: 'o',
  };

  for (const [kan, rom] of Object.entries(smallLetters)) {
    subtreeOf(kan)[''] = rom;
  }

  return Object.freeze(JSON.parse(JSON.stringify(romajiTree)));
}

function getKanaToHepburnTree() {
  if (kanaToHepburnMap === null) {
    kanaToHepburnMap = createKanaToHepburnMap();
  }
  return kanaToHepburnMap;
}

export function getRomajiPostProcessing(fullOptions) {
  switch (fullOptions.romanization) {
    case methods.HEPBURN:
      return getHepburnPostProcessing(fullOptions);
    default:
      return ([kana, parsed]) => [kana, parsed];
  }
}

export function getKanaToRomajiTree(fullOptions) {
  switch (fullOptions.romanization) {
    case methods.HEPBURN:
      return getKanaToHepburnTree(fullOptions);
    default:
      return {};
  }
}

function getHepburnPostProcessing(fullOptions) {
  return function postProcessing([kana, parsed]) {
    const labial = ['b', 'm', 'p'];
    const vowels = ['a', 'i', 'u', 'e', 'o', 'y'];
    const newParsed = JSON.parse(JSON.stringify(parsed));
    for (let index = 0; index < parsed.length; index += 1) {
      const start = parsed[index][0];
      if (katakanaToHiragana(kana.charAt(start)) === 'ん') {
        const nextElement = parsed[index + 1];
        if (nextElement !== undefined) {
          const nextChar = nextElement[2].charAt(0);
          switch (true) {
            // んば -> mba
            case labial.includes(nextChar):
              newParsed[index][2] = 'm';
              break;
            // んや -> n'ya
            case vowels.includes(nextChar):
              newParsed[index][2] = 'n\'';
              break;
          }
        }
      }
      if (fullOptions.upcaseKatakana) {
        const [begin, end, romaji] = newParsed[index];
        if (isKatakana(kana.slice(begin, end))) {
          newParsed[index][2] = romaji.toUpperCase();
        }
      }
    }
    return [kana, newParsed];
  };
}
<commit_msg>Compactify the objects to make them nicer to read<commit_after>import { transform, getSubTreeOf } from './kanaMappingUtils';
import isKatakana from './isKatakana';
import katakanaToHiragana from './utils/katakanaToHiragana';

export const methods = Object.freeze({
  HEPBURN: 'hepburn',
});

let kanaToHepburnMap = null;

function createKanaToHepburnMap() {
  /* eslint-disable object-property-newline */
  const romajiTree = transform({
    あ: 'a', い: 'i', う: 'u', え: 'e', お: 'o',
    か: 'ka', き: 'ki', く: 'ku', け: 'ke', こ: 'ko',
    さ: 'sa', し: 'shi', す: 'su', せ: 'se', そ: 'so',
    た: 'ta', ち: 'chi', つ: 'tsu', て: 'te', と: 'to',
    な: 'na', に: 'ni', ぬ: 'nu', ね: 'ne', の: 'no',
    は: 'ha', ひ: 'hi', ふ: 'fu', へ: 'he', ほ: 'ho',
    ま: 'ma', み: 'mi', む: 'mu', め: 'me', も: 'mo',
    や: 'ya', ゆ: 'yu', よ: 'yo',
    ら: 'ra', り: 'ri', る: 'ru', れ: 're', ろ: 'ro',
    わ: 'wa', ゐ: 'wi', ゑ: 'we', を: 'wo',
    が: 'ga', ぎ: 'gi', ぐ: 'gu', げ: 'ge', ご: 'go',
    ざ: 'za', じ: 'ji', ず: 'zu', ぜ: 'ze', ぞ: 'zo',
    だ: 'da', ぢ: 'ji', づ: 'zu', で: 'de', ど: 'do',
    ば: 'ba', び: 'bi', ぶ: 'bu', べ: 'be', ぼ: 'bo',
    ぱ: 'pa', ぴ: 'pi', ぷ: 'pu', ぺ: 'pe', ぽ: 'po',
    ゔぁ: 'va', ゔぃ: 'vi', ゔ: 'vu', ゔぇ: 've', ゔぉ: 'vo',
    ん: 'n',
  });

  const subtreeOf = (string) => getSubTreeOf(romajiTree, string);

  const specialSymbols = {
    '。': '.', '、': ',',
    '：': ':', '・': '/',
    '！': '!', '？': '?',
    '〜': '~', 'ー': '-',
    '「': '‘', '」': '’',
    '『': '“', '』': '”',
    '［': '[', '］': ']',
    '（': '(', '）': ')',
    '｛': '{', '｝': '}',
    '　': ' ',
  };

  for (const [jsymbol, symbol] of Object.entries(specialSymbols)) {
    subtreeOf(jsymbol)[''] = symbol;
  }

  const smallY = { ゃ: 'ya', ゅ: 'yu', ょ: 'yo' };
  const smallYExtra = { ぃ: 'yi', ぇ: 'ye' };
  const smallaiueo = { ぁ: 'a', ぃ: 'i', ぅ: 'u', ぇ: 'e', ぉ: 'o' };

  for (const [rom, kan] of Object.entries(smallY).concat(Object.entries(smallaiueo))) {
    subtreeOf(rom)[''] = kan;
  }

  const yoonKana = ['き', 'に', 'ひ', 'み', 'り', 'ぎ', 'び', 'ぴ', 'ゔ', 'く', 'ふ'];
  // きゃ -> kya
  for (const kana of yoonKana) {
    const fistRomajiLetter = subtreeOf(kana)[''][0];
    for (const [yKan, yRom] of Object.entries(smallY)) {
      subtreeOf(kana + yKan)[''] = fistRomajiLetter + yRom;
    }
    // きぃ -> kyi
    for (const [yKan, yRom] of Object.entries(smallYExtra)) {
      subtreeOf(kana + yKan)[''] = fistRomajiLetter + yRom;
    }
  }
  const yoonExceptions = { し: 'sh', ち: 'ch', じ: 'j', ぢ: 'j' };
  for (const [kana, rom] of Object.entries(yoonExceptions)) {
    // じゃ -> ja
    for (const [yKan, yRom] of Object.entries(smallY)) {
      subtreeOf(kana + yKan)[''] = rom + yRom[1];
    }
    // じぃ -> jyi, じぇ -> je
    subtreeOf(`${kana}ぃ`)[''] = `${rom}yi`;
    subtreeOf(`${kana}ぇ`)[''] = `${rom}e`;
  }

  // going with the intuitive (yet incorrect) solution where っや -> yya and っぃ -> ii
  // in other words, just assume the sokuon could have been applied to anything

  const sokuonWhitelist = {
    b: 'b',
    c: 't',
    d: 'd',
    f: 'f',
    g: 'g',
    h: 'h',
    j: 'j',
    k: 'k',
    m: 'm',
    p: 'p',
    q: 'q',
    r: 'r',
    s: 's',
    t: 't',
    v: 'v',
    w: 'w',
    x: 'x',
    z: 'z',
  };

  function resolveTsu(tree) {
    const result = {};
    for (const [key, value] of Object.entries(tree)) {
      if (!key) {  // we have reached the bottom of this branch
        const consonant = value.charAt(0);
        result[key] = consonant in sokuonWhitelist?
          sokuonWhitelist[consonant] + value:
          value;
      } else {  // more subtrees
        result[key] = resolveTsu(value);
      }
    }
    return result;
  }

  romajiTree['っ'] = resolveTsu(romajiTree);

  const smallLetters = {
    っ: '',
    ゎ: 'wa',
    ゕ: 'ka',
    ゖ: 'ka',  // because katakana is converted to hiragana before calling this function
    ゃ: 'ya',
    ゅ: 'yu',
    ょ: 'yo',
    ぁ: 'a',
    ぃ: 'i',
    ぅ: 'u',
    ぇ: 'e',
    ぉ: 'o',
  };

  for (const [kan, rom] of Object.entries(smallLetters)) {
    subtreeOf(kan)[''] = rom;
  }

  return Object.freeze(JSON.parse(JSON.stringify(romajiTree)));
  /* eslint-enable no-alert, no-console */
}

function getKanaToHepburnTree() {
  if (kanaToHepburnMap === null) {
    kanaToHepburnMap = createKanaToHepburnMap();
  }
  return kanaToHepburnMap;
}

export function getRomajiPostProcessing(fullOptions) {
  switch (fullOptions.romanization) {
    case methods.HEPBURN:
      return getHepburnPostProcessing(fullOptions);
    default:
      return ([kana, parsed]) => [kana, parsed];
  }
}

export function getKanaToRomajiTree(fullOptions) {
  switch (fullOptions.romanization) {
    case methods.HEPBURN:
      return getKanaToHepburnTree(fullOptions);
    default:
      return {};
  }
}

function getHepburnPostProcessing(fullOptions) {
  return function postProcessing([kana, parsed]) {
    const labial = ['b', 'm', 'p'];
    const vowels = ['a', 'i', 'u', 'e', 'o', 'y'];
    const newParsed = JSON.parse(JSON.stringify(parsed));
    for (let index = 0; index < parsed.length; index += 1) {
      const start = parsed[index][0];
      if (katakanaToHiragana(kana.charAt(start)) === 'ん') {
        const nextElement = parsed[index + 1];
        if (nextElement !== undefined) {
          const nextChar = nextElement[2].charAt(0);
          switch (true) {
            // んば -> mba
            case labial.includes(nextChar):
              newParsed[index][2] = 'm';
              break;
            // んや -> n'ya
            case vowels.includes(nextChar):
              newParsed[index][2] = 'n\'';
              break;
          }
        }
      }
      if (fullOptions.upcaseKatakana) {
        const [begin, end, romaji] = newParsed[index];
        if (isKatakana(kana.slice(begin, end))) {
          newParsed[index][2] = romaji.toUpperCase();
        }
      }
    }
    return [kana, newParsed];
  };
}
<|endoftext|>


<commit_before>import EmberView from "ember-views/views/view";
import run from "ember-metal/run_loop";
import { compile } from "htmlbars-compiler/compiler";
import { equalInnerHTML } from "htmlbars-test-helpers";

var view;

function appendView(view) {
  run(function() { view.appendTo('#qunit-fixture'); });
}

if (Ember.FEATURES.isEnabled('ember-htmlbars-attribute-syntax')) {

QUnit.module("ember-htmlbars: class attribute", {
  teardown: function(){
    if (view) {
      run(view, view.destroy);
    }
  }
});

test("class property can contain multiple classes", function() {
  view = EmberView.create({
    context: {classes: 'large blue'},
    template: compile("

")
  });
  appendView(view);

  equalInnerHTML(view.element, '

',
                 "attribute is output");
  ok(view.$('.large')[0], 'first class found');
  ok(view.$('.blue')[0], 'second class found');
});

test("class property is removed when updated with a null value", function() {
  view = EmberView.create({
    context: {class: 'large'},
    template: compile("

")
  });
  appendView(view);

  equalInnerHTML(view.element, '

',
                 "attribute is output");

  run(view, view.set, 'context.class', null);

  equalInnerHTML(view.element, '

',
                 "attribute is removed");
});

test("class attribute concats bound values", function() {
  view = EmberView.create({
    context: {size: 'large', color: 'blue'},
    template: compile("

")
  });
  appendView(view);

  ok(view.$('.large')[0], 'first class found');
  ok(view.$('.blue')[0], 'second class found');
  ok(view.$('.round')[0], 'third class found');
});

test("class attribute accepts nested helpers, and updates", function() {
  view = EmberView.create({
    context: {
      size: 'large',
      hasColor: true,
      hasShape: false,
      shape: 'round'
    },
    template: compile("

")
  });
  appendView(view);

  ok(view.$('.large')[0], 'first class found');
  ok(view.$('.blue')[0], 'second class found');
  ok(view.$('.no-shape')[0], 'third class found');

  run(view, view.set, 'context.hasColor', false);
  run(view, view.set, 'context.hasShape', true);

  ok(view.$('.large')[0], 'first class found after change');
  ok(view.$('.blue').length === 0, 'second class not found after change');
  ok(view.$('.round')[0], 'third class found after change');
});

test("class attribute can accept multipe classes from a single value, and update", function() {
  view = EmberView.create({
    context: {
      size: 'large small'
    },
    template: compile("

")
  });
  appendView(view);

  ok(view.$('.large')[0], 'first class found');
  ok(view.$('.small')[0], 'second class found');

  run(view, view.set, 'context.size', 'medium');

  ok(view.$('.large').length === 0, 'old class not found');
  ok(view.$('.small').length === 0, 'old class not found');
  ok(view.$('.medium')[0], 'new class found');
});

}
<commit_msg>inline-if test for classes should expect that feature flag<commit_after>import EmberView from "ember-views/views/view";
import run from "ember-metal/run_loop";
import { compile } from "htmlbars-compiler/compiler";
import { equalInnerHTML } from "htmlbars-test-helpers";

var view;

function appendView(view) {
  run(function() { view.appendTo('#qunit-fixture'); });
}

var isInlineIfEnabled = false;
if (Ember.FEATURES.isEnabled('ember-htmlbars-inline-if-helper')) {
  isInlineIfEnabled = true;
}

if (Ember.FEATURES.isEnabled('ember-htmlbars-attribute-syntax')) {

QUnit.module("ember-htmlbars: class attribute", {
  teardown: function(){
    if (view) {
      run(view, view.destroy);
    }
  }
});

test("class property can contain multiple classes", function() {
  view = EmberView.create({
    context: {classes: 'large blue'},
    template: compile("

")
  });
  appendView(view);

  equalInnerHTML(view.element, '

',
                 "attribute is output");
  ok(view.$('.large')[0], 'first class found');
  ok(view.$('.blue')[0], 'second class found');
});

test("class property is removed when updated with a null value", function() {
  view = EmberView.create({
    context: {class: 'large'},
    template: compile("

")
  });
  appendView(view);

  equalInnerHTML(view.element, '

',
                 "attribute is output");

  run(view, view.set, 'context.class', null);

  equalInnerHTML(view.element, '

',
                 "attribute is removed");
});

test("class attribute concats bound values", function() {
  view = EmberView.create({
    context: {size: 'large', color: 'blue'},
    template: compile("

")
  });
  appendView(view);

  ok(view.$('.large')[0], 'first class found');
  ok(view.$('.blue')[0], 'second class found');
  ok(view.$('.round')[0], 'third class found');
});

if (isInlineIfEnabled) {

test("class attribute accepts nested helpers, and updates", function() {
  view = EmberView.create({
    context: {
      size: 'large',
      hasColor: true,
      hasShape: false,
      shape: 'round'
    },
    template: compile("

")
  });
  appendView(view);

  ok(view.$('.large')[0], 'first class found');
  ok(view.$('.blue')[0], 'second class found');
  ok(view.$('.no-shape')[0], 'third class found');

  run(view, view.set, 'context.hasColor', false);
  run(view, view.set, 'context.hasShape', true);

  ok(view.$('.large')[0], 'first class found after change');
  ok(view.$('.blue').length === 0, 'second class not found after change');
  ok(view.$('.round')[0], 'third class found after change');
});

}

test("class attribute can accept multipe classes from a single value, and update", function() {
  view = EmberView.create({
    context: {
      size: 'large small'
    },
    template: compile("

")
  });
  appendView(view);

  ok(view.$('.large')[0], 'first class found');
  ok(view.$('.small')[0], 'second class found');

  run(view, view.set, 'context.size', 'medium');

  ok(view.$('.large').length === 0, 'old class not found');
  ok(view.$('.small').length === 0, 'old class not found');
  ok(view.$('.medium')[0], 'new class found');
});

}
<|endoftext|>


<commit_before>// Bundle each javascript module with Browserify
// This script will fetch all main files for each module and will generate an ES6 compatible module with

module.exports = (GULP, PLUGINS, NODE_MODULES, REVISION) => {
    return function (callback) {

        // Define all module locations in a globbing pattern (including your external packages: bower, NPM etc.)
        var data = [
            {
                'path': process.env.SRC + '/resources/templates/*/javascripts/*.js',
                'type': 'template'
            },
            {
                'path': process.env.SRC + '/resources/groups/*/javascripts/*.js',
                'type': 'group'
            },
            {
                'path': process.env.SRC + '/resources/modules/*/javascripts/*.js',
                'type': 'group'
            },
            {
                'path': process.env.SUBMODULES_PATH + '/totem.module.*/javascripts/*.js',
                'type': 'module'
            }
        ];

        var sources = [];
        data.forEach(function (source) {
            sources.push(source.path);
        }, this);

        //Define a stream we can return to complete our task
        var streams = [];

        return NODE_MODULES.globby(sources).then(files => {
            for (var index = 0; index < files.length; index++) {

                var stats = NODE_MODULES.fse.statSync(files[index]);

                var basename = NODE_MODULES.path.basename(files[index]);
                var ext = NODE_MODULES.path.extname(basename);
                var name = NODE_MODULES.path.basename(files[index], ext);

                if (stats.size === 0) {
                    PLUGINS.util.log(NODE_MODULES.chalk.yellow(name + ext + ' is empty, this file will be ignored.'))
                    break;
                }

                var subfolder = '';
                switch (data[index].type) {
                    case 'template':
                        subfolder = '/resources/templates/';
                        break;
                    case 'group':
                        subfolder = '/resources/groups/';
                        break;
                    default:
                        subfolder = '/resources/modules/';
                        break;
                }

                var queue = NODE_MODULES.browserify({
                    entries: files[index],
                    standalone: NODE_MODULES.camelCase(name)
                }).transform(NODE_MODULES.babelify).bundle()
                    .pipe(NODE_MODULES.vinylSourceStream(basename))
                    .pipe(PLUGINS.derequire())
                    .pipe(GULP.dest(process.env.DEST + subfolder + name + '/javascripts'));

                streams.push(queue);
            }

            return NODE_MODULES.merge(streams);
        });
    }
}<commit_msg>Browserify Transform modules & groups<commit_after>// Bundle each javascript module with Browserify
// This script will fetch all main files for each module and will generate an ES6 compatible module with

module.exports = (GULP, PLUGINS, NODE_MODULES, REVISION) => {
    return function (callback) {

        // Define all module locations in a globbing pattern (including your external packages: bower, NPM etc.)
        var data = [
            {
                'path': process.env.SRC + '/resources/modules/*/javascripts/*.js',
                'type': 'module'
            },
            {
                'path': process.env.SUBMODULES_PATH + '/totem.module.*/javascripts/*.js',
                'type': 'module'
            },
            {
                'path': process.env.SRC + '/resources/groups/*/javascripts/*.js',
                'type': 'group'
            },
            {
                'path': process.env.SRC + '/resources/templates/*/javascripts/*.js',
                'type': 'template'
            }
        ];

        var streams = [];

        // Iterate trough all types and iterate over it
        data.forEach(function (source) {
            NODE_MODULES.globby(source.path).then(files => {
                for (var index = 0; index < files.length; index++) {
                    var stats = NODE_MODULES.fse.statSync(files[index]);

                    var basename = NODE_MODULES.path.basename(files[index]);
                    var ext = NODE_MODULES.path.extname(basename);
                    var name = NODE_MODULES.path.basename(files[index], ext);

                    if (stats.size === 0) {
                        PLUGINS.util.log(NODE_MODULES.chalk.yellow(name + ext + ' is empty, this file will be ignored.'))
                        continue;
                    }

                    PLUGINS.util.log(NODE_MODULES.chalk.yellow(name + ext + ' is not empty'))

                    var subfolder = '';
                    switch (source.type) {
                        case 'template':
                            subfolder = '/resources/templates/';
                            break;
                        case 'group':
                            subfolder = '/resources/groups/';
                            break;
                        default:
                            subfolder = '/resources/modules/';
                            break;
                    }

                    var stream = NODE_MODULES.browserify({
                        entries: files[index],
                        standalone: NODE_MODULES.camelCase(name)
                    }).transform(NODE_MODULES.babelify).bundle()
                        .pipe(NODE_MODULES.vinylSourceStream(basename))
                        .pipe(PLUGINS.derequire())
                        .pipe(GULP.dest(process.env.DEST + subfolder + name + '/javascripts'));

                    streams.push(stream);
                }
            });

        }, this);

        return NODE_MODULES.merge(streams);
    }
}<|endoftext|>


<commit_before>}(window, document));
<commit_msg>Returned the internal var to the global.<commit_after>	return hyperaudio;
}(window, document));
<|endoftext|>


<commit_before>!function(r){function o(e){if(n[e])return n[e].exports;var t=n[e]={exports:{},id:e,loaded:!1};return r[e].call(t.exports,t,t.exports,o),t.loaded=!0,t.exports}var n={};return o.m=r,o.c=n,o.p="",o(0)}([function(r,o,n){"use strict";var e=n(1),t=n(4);_rollbarConfig=_rollbarConfig||{},_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||"https://cdnjs.cloudflare.com/ajax/libs/rollbar.js/2.1.1/rollbar.min.js",_rollbarConfig.async=void 0===_rollbarConfig.async||_rollbarConfig.async;var l=e.setupShim(window,_rollbarConfig),a=t(_rollbarConfig);window.rollbar=e.Rollbar,l.loadFull(window,document,!_rollbarConfig.async,_rollbarConfig,a)},function(r,o,n){"use strict";function e(r){return function(){try{return r.apply(this,arguments)}catch(r){try{console.error("[Rollbar]: Internal error",r)}catch(r){}}}}function t(r,o){this.options=r,this._rollbarOldOnError=null;var n=s++;this.shimId=function(){return n},window&&window._rollbarShims&&(window._rollbarShims[n]={handler:o,messages:[]})}function l(r,o){var n=o.globalAlias||"Rollbar";if("object"==typeof r[n])return r[n];r._rollbarShims={},r._rollbarWrappedError=null;var t=new d(o);return e(function(){return o.captureUncaught&&(t._rollbarOldOnError=r.onerror,i.captureUncaughtExceptions(r,t,!0),i.wrapGlobals(r,t,!0)),o.captureUnhandledRejections&&i.captureUnhandledRejections(r,t,!0),r[n]=t,t})()}function a(r){return e(function(){var o=this,n=Array.prototype.slice.call(arguments,0),e={shim:o,method:r,args:n,ts:new Date};window._rollbarShims[this.shimId()].messages.push(e)})}var i=n(2),s=0,c=n(3),p=function(r,o){return new t(r,o)},d=c.bind(null,p);t.prototype.loadFull=function(r,o,n,t,l){var a=function(){var o;if(void 0===r._rollbarDidLoad){o=new Error("rollbar.js did not load");for(var n,e,t,a,i=0;n=r._rollbarShims[i++];)for(n=n.messages||[];e=n.shift();)for(t=e.args||[],i=0;i<t.length;++i)if(a=t[i],"function"==typeof a){a(o);break}}"function"==typeof l&&l(o)},i=!1,s=o.createElement("script"),c=o.getElementsByTagName("script")[0],p=c.parentNode;s.crossOrigin="",s.src=t.rollbarJsUrl,n||(s.async=!0),s.onload=s.onreadystatechange=e(function(){if(!(i||this.readyState&&"loaded"!==this.readyState&&"complete"!==this.readyState)){s.onload=s.onreadystatechange=null;try{p.removeChild(s)}catch(r){}i=!0,a()}}),p.insertBefore(s,c)},t.prototype.wrap=function(r,o){try{var n;if(n="function"==typeof o?o:function(){return o||{}},"function"!=typeof r)return r;if(r._isWrap)return r;if(!r._rollbar_wrapped&&(r._rollbar_wrapped=function(){try{return r.apply(this,arguments)}catch(e){var o=e;throw"string"==typeof o&&(o=new String(o)),o._rollbarContext=n()||{},o._rollbarContext._wrappedSource=r.toString(),window._rollbarWrappedError=o,o}},r._rollbar_wrapped._isWrap=!0,r.hasOwnProperty))for(var e in r)r.hasOwnProperty(e)&&(r._rollbar_wrapped[e]=r[e]);return r._rollbar_wrapped}catch(o){return r}};for(var u="log,debug,info,warn,warning,error,critical,global,configure,handleUncaughtException,handleUnhandledRejection".split(","),f=0;f<u.length;++f)t.prototype[u[f]]=a(u[f]);r.exports={setupShim:l,Rollbar:d}},function(r,o){"use strict";function n(r,o,n){if(r){var t;"function"==typeof o._rollbarOldOnError?t=o._rollbarOldOnError:r.onerror&&!r.onerror.belongsToShim&&(t=r.onerror,o._rollbarOldOnError=t);var l=function(){var n=Array.prototype.slice.call(arguments,0);e(r,o,t,n)};l.belongsToShim=n,r.onerror=l}}function e(r,o,n,e){r._rollbarWrappedError&&(e[4]||(e[4]=r._rollbarWrappedError),e[5]||(e[5]=r._rollbarWrappedError._rollbarContext),r._rollbarWrappedError=null),o.handleUncaughtException.apply(o,e),n&&n.apply(r,e)}function t(r,o,n){if(r){"function"==typeof r._rollbarURH&&r._rollbarURH.belongsToShim&&r.removeEventListener("unhandledrejection",r._rollbarURH);var e=function(r){var n=r.reason,e=r.promise,t=r.detail;!n&&t&&(n=t.reason,e=t.promise),o&&o.handleUnhandledRejection&&o.handleUnhandledRejection(n,e)};e.belongsToShim=n,r._rollbarURH=e,r.addEventListener("unhandledrejection",e)}}function l(r,o,n){if(r){var e,t,l="EventTarget,Window,Node,ApplicationCache,AudioTrackList,ChannelMergerNode,CryptoOperation,EventSource,FileReader,HTMLUnknownElement,IDBDatabase,IDBRequest,IDBTransaction,KeyOperation,MediaController,MessagePort,ModalWindow,Notification,SVGElementInstance,Screen,TextTrack,TextTrackCue,TextTrackList,WebSocket,WebSocketWorker,Worker,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload".split(",");for(e=0;e<l.length;++e)t=l[e],r[t]&&r[t].prototype&&a(o,r[t].prototype,n)}}function a(r,o,n){if(o.hasOwnProperty&&o.hasOwnProperty("addEventListener")){for(var e=o.addEventListener;e._rollbarOldAdd&&e.belongsToShim;)e=e._rollbarOldAdd;var t=function(o,n,t){e.call(this,o,r.wrap(n),t)};t._rollbarOldAdd=e,t.belongsToShim=n,o.addEventListener=t;for(var l=o.removeEventListener;l._rollbarOldRemove&&l.belongsToShim;)l=l._rollbarOldRemove;var a=function(r,o,n){l.call(this,r,o&&o._rollbar_wrapped||o,n)};a._rollbarOldRemove=l,a.belongsToShim=n,o.removeEventListener=a}}r.exports={captureUncaughtExceptions:n,captureUnhandledRejections:t,wrapGlobals:l}},function(r,o){"use strict";function n(r,o){this.impl=r(o,this),this.options=o,e(n.prototype)}function e(r){for(var o=function(r){return function(){var o=Array.prototype.slice.call(arguments,0);if(this.impl[r])return this.impl[r].apply(this.impl,o)}},n="log,debug,info,warn,warning,error,critical,global,configure,handleUncaughtException,handleUnhandledRejection,_createItem,wrap,loadFull,shimId".split(","),e=0;e<n.length;e++)r[n[e]]=o(n[e])}n.prototype._swapAndProcessMessages=function(r,o){this.impl=r(this.options);for(var n,e,t;n=o.shift();)e=n.method,t=n.args,this[e]&&"function"==typeof this[e]&&this[e].apply(this,t);return this},r.exports=n},function(r,o){"use strict";r.exports=function(r){return function(o){if(!o&&!window._rollbarInitialized){r=r||{};for(var n,e,t=r.globalAlias||"Rollbar",l=window.rollbar,a=function(r){return new l(r)},i=0;n=window._rollbarShims[i++];)e||(e=n.handler),n.handler._swapAndProcessMessages(a,n.messages);window[t]=e,window._rollbarInitialized=!0}}}}]);<commit_msg>Update stored rollbar.js snippet to the recent version<commit_after>!function(r){function o(n){if(e[n])return e[n].exports;var t=e[n]={exports:{},id:n,loaded:!1};return r[n].call(t.exports,t,t.exports,o),t.loaded=!0,t.exports}var e={};return o.m=r,o.c=e,o.p="",o(0)}([function(r,o,e){"use strict";var n=e(1),t=e(4);_rollbarConfig=_rollbarConfig||{},_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||"https://cdnjs.cloudflare.com/ajax/libs/rollbar.js/2.2.3/rollbar.min.js",_rollbarConfig.async=void 0===_rollbarConfig.async||_rollbarConfig.async;var a=n.setupShim(window,_rollbarConfig),l=t(_rollbarConfig);window.rollbar=n.Rollbar,a.loadFull(window,document,!_rollbarConfig.async,_rollbarConfig,l)},function(r,o,e){"use strict";function n(r){return function(){try{return r.apply(this,arguments)}catch(r){try{console.error("[Rollbar]: Internal error",r)}catch(r){}}}}function t(r,o){this.options=r,this._rollbarOldOnError=null;var e=s++;this.shimId=function(){return e},window&&window._rollbarShims&&(window._rollbarShims[e]={handler:o,messages:[]})}function a(r,o){var e=o.globalAlias||"Rollbar";if("object"==typeof r[e])return r[e];r._rollbarShims={},r._rollbarWrappedError=null;var t=new p(o);return n(function(){o.captureUncaught&&(t._rollbarOldOnError=r.onerror,i.captureUncaughtExceptions(r,t,!0),i.wrapGlobals(r,t,!0)),o.captureUnhandledRejections&&i.captureUnhandledRejections(r,t,!0);var n=o.autoInstrument;return(void 0===n||n===!0||"object"==typeof n&&n.network)&&r.addEventListener&&(r.addEventListener("load",t.captureLoad.bind(t)),r.addEventListener("DOMContentLoaded",t.captureDomContentLoaded.bind(t))),r[e]=t,t})()}function l(r){return n(function(){var o=this,e=Array.prototype.slice.call(arguments,0),n={shim:o,method:r,args:e,ts:new Date};window._rollbarShims[this.shimId()].messages.push(n)})}var i=e(2),s=0,d=e(3),c=function(r,o){return new t(r,o)},p=d.bind(null,c);t.prototype.loadFull=function(r,o,e,t,a){var l=function(){var o;if(void 0===r._rollbarDidLoad){o=new Error("rollbar.js did not load");for(var e,n,t,l,i=0;e=r._rollbarShims[i++];)for(e=e.messages||[];n=e.shift();)for(t=n.args||[],i=0;i<t.length;++i)if(l=t[i],"function"==typeof l){l(o);break}}"function"==typeof a&&a(o)},i=!1,s=o.createElement("script"),d=o.getElementsByTagName("script")[0],c=d.parentNode;s.crossOrigin="",s.src=t.rollbarJsUrl,e||(s.async=!0),s.onload=s.onreadystatechange=n(function(){if(!(i||this.readyState&&"loaded"!==this.readyState&&"complete"!==this.readyState)){s.onload=s.onreadystatechange=null;try{c.removeChild(s)}catch(r){}i=!0,l()}}),c.insertBefore(s,d)},t.prototype.wrap=function(r,o,e){try{var n;if(n="function"==typeof o?o:function(){return o||{}},"function"!=typeof r)return r;if(r._isWrap)return r;if(!r._rollbar_wrapped&&(r._rollbar_wrapped=function(){e&&"function"==typeof e&&e.apply(this,arguments);try{return r.apply(this,arguments)}catch(e){var o=e;throw"string"==typeof o&&(o=new String(o)),o._rollbarContext=n()||{},o._rollbarContext._wrappedSource=r.toString(),window._rollbarWrappedError=o,o}},r._rollbar_wrapped._isWrap=!0,r.hasOwnProperty))for(var t in r)r.hasOwnProperty(t)&&(r._rollbar_wrapped[t]=r[t]);return r._rollbar_wrapped}catch(o){return r}};for(var u="log,debug,info,warn,warning,error,critical,global,configure,handleUncaughtException,handleUnhandledRejection,captureDomContentLoaded,captureLoad".split(","),f=0;f<u.length;++f)t.prototype[u[f]]=l(u[f]);r.exports={setupShim:a,Rollbar:p}},function(r,o){"use strict";function e(r,o,e){if(r){var t;"function"==typeof o._rollbarOldOnError?t=o._rollbarOldOnError:r.onerror&&!r.onerror.belongsToShim&&(t=r.onerror,o._rollbarOldOnError=t);var a=function(){var e=Array.prototype.slice.call(arguments,0);n(r,o,t,e)};a.belongsToShim=e,r.onerror=a}}function n(r,o,e,n){r._rollbarWrappedError&&(n[4]||(n[4]=r._rollbarWrappedError),n[5]||(n[5]=r._rollbarWrappedError._rollbarContext),r._rollbarWrappedError=null),o.handleUncaughtException.apply(o,n),e&&e.apply(r,n)}function t(r,o,e){if(r){"function"==typeof r._rollbarURH&&r._rollbarURH.belongsToShim&&r.removeEventListener("unhandledrejection",r._rollbarURH);var n=function(r){var e=r.reason,n=r.promise,t=r.detail;!e&&t&&(e=t.reason,n=t.promise),o&&o.handleUnhandledRejection&&o.handleUnhandledRejection(e,n)};n.belongsToShim=e,r._rollbarURH=n,r.addEventListener("unhandledrejection",n)}}function a(r,o,e){if(r){var n,t,a="EventTarget,Window,Node,ApplicationCache,AudioTrackList,ChannelMergerNode,CryptoOperation,EventSource,FileReader,HTMLUnknownElement,IDBDatabase,IDBRequest,IDBTransaction,KeyOperation,MediaController,MessagePort,ModalWindow,Notification,SVGElementInstance,Screen,TextTrack,TextTrackCue,TextTrackList,WebSocket,WebSocketWorker,Worker,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload".split(",");for(n=0;n<a.length;++n)t=a[n],r[t]&&r[t].prototype&&l(o,r[t].prototype,e)}}function l(r,o,e){if(o.hasOwnProperty&&o.hasOwnProperty("addEventListener")){for(var n=o.addEventListener;n._rollbarOldAdd&&n.belongsToShim;)n=n._rollbarOldAdd;var t=function(o,e,t){n.call(this,o,r.wrap(e),t)};t._rollbarOldAdd=n,t.belongsToShim=e,o.addEventListener=t;for(var a=o.removeEventListener;a._rollbarOldRemove&&a.belongsToShim;)a=a._rollbarOldRemove;var l=function(r,o,e){a.call(this,r,o&&o._rollbar_wrapped||o,e)};l._rollbarOldRemove=a,l.belongsToShim=e,o.removeEventListener=l}}r.exports={captureUncaughtExceptions:e,captureUnhandledRejections:t,wrapGlobals:a}},function(r,o){"use strict";function e(r,o){this.impl=r(o,this),this.options=o,n(e.prototype)}function n(r){for(var o=function(r){return function(){var o=Array.prototype.slice.call(arguments,0);if(this.impl[r])return this.impl[r].apply(this.impl,o)}},e="log,debug,info,warn,warning,error,critical,global,configure,handleUncaughtException,handleUnhandledRejection,_createItem,wrap,loadFull,shimId,captureDomContentLoaded,captureLoad".split(","),n=0;n<e.length;n++)r[e[n]]=o(e[n])}e.prototype._swapAndProcessMessages=function(r,o){this.impl=r(this.options);for(var e,n,t;e=o.shift();)n=e.method,t=e.args,this[n]&&"function"==typeof this[n]&&("captureDomContentLoaded"===n||"captureLoad"===n?this[n].apply(this,[t[0],e.ts]):this[n].apply(this,t));return this},r.exports=e},function(r,o){"use strict";r.exports=function(r){return function(o){if(!o&&!window._rollbarInitialized){r=r||{};for(var e,n,t=r.globalAlias||"Rollbar",a=window.rollbar,l=function(r){return new a(r)},i=0;e=window._rollbarShims[i++];)n||(n=e.handler),e.handler._swapAndProcessMessages(l,e.messages);window[t]=n,window._rollbarInitialized=!0}}}}]);<|endoftext|>


<commit_before>/**
 * cbpAnimatedHeader.min.js v1.0.0
 * http://www.codrops.com
 *
 * Licensed under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright 2013, Codrops
 * http://www.codrops.com
 */
var cbpAnimatedHeader=(function(){var b=document.documentElement,g=document.querySelector(".cbp-af-header"),e=false,a=300;function f(){window.addEventListener("scroll",function(h){if(!e){e=true;setTimeout(d,250)}},false)}function d(){var h=c();if(h>=a){classie.add(g,"cbp-af-header-shrink")}else{classie.remove(g,"cbp-af-header-shrink")}e=false}function c(){return window.pageYOffset||b.scrollTop}f()})();<commit_msg>Delete cbpAnimatedHeader.min.js<commit_after><|endoftext|>


<commit_before>async function(args) {
/*
created_timestamp(-1)
base_component_id("app_editor_3")
is_app(true)
display_name("Editor App V3")
description("This will return the editor app V3")
visibility("PUBLIC")
logo_url("https://2.bp.blogspot.com/-6Hdixw3dFxk/WfSQOnB9lDI/AAAAAAAAFFc/84DRGgcwOpYBOgknkHQ-qmgxvFv1D-iHACLcBGAs/s1600/BracketsDarks.PNG")
load_once_from_file(true)
*/

    var argBaseComponentId = args.base_component_id
    var cardId = args.card_id

    var mm = null
    Vue.component("app_editor_3",
    {
      template: `

                    App Editor V3

{{app_component_name?app_component_name.substring(0,30):""}}{{(app_component_name && ((app_component_name.length > 30))?"...":"")}}

                            <button  type=button class='btn btn-primary'      v-on:click='chooseApp()'  >App</button>
                            <button  type=button class=' btn btn-secondary'   v-on:click='chooseCode()' >Code</button>
                            <button  type=button class=' btn btn-info'        v-on:click='chooseBoth()' >Both</button>
                            <button  type=button class=' btn btn-secondary'   v-on:click='copyAppMethod(base_component_id)' >Copy app</button>
                            <button  type=button class=' btn btn-info'        v-on:click='prepareApp(card_id, \"appEmbed\", {base_component_id: base_component_id})' >Embed app</button>

                      Sorry, you can't view or edit the AppShare editor without an application to edit

                    <select class="custom-select" v-model="selected_app" v-bind:onchange='load_app(selected_app)'>
                      <option selected>Open this select menu</option>
                      <option v-for='app in apps'
                              v-bind:value="app.base_component_id"
                              >{{app.display_name}}</option>
                    </select>

                      <component  v-bind:is="editor_component" v-if="editor_loaded" ref="editorComponentRef">
                                      <button v-bind:style="'visibility: ' + ((app_shown && code_shown)?'':'hidden')"
                                              slot-scope="editor_component"
                                              v-on:click='save(base_component_id, code_id, editor_component.text2)'
                                              type="button" class="btn btn-primary">

                                                  Update App
                                     </button>
                      </component>

                      <component  v-bind:is="app_component_name" v-if="app_loaded">
                        APP HERE
                      </component>

       `
       ,
       data: function() {
           return {
               editor_loaded:       false,
               selected_app:        null,
               editor_component:    null,
               app_loaded:          false,
               apps:               [],
               app_component_name:  null,
               base_component_id:   null,
               code_id:            "...",
               version: 0,
               card_id: null,
               app_width:           "33%",
               code_width:          "63%",
               app_shown:           true,
               code_shown:          true
           }
       }
       ,
       methods: {
            // ---------------------------------------------------------------
            //                         chooseApp
            //
            // This is called when the end user selects an app from the menu
            // ---------------------------------------------------------------
            chooseApp: function() {
                this.code_width = "0%"
                this.code_shown = false

                this.app_width = "95%"
                this.app_shown = true

                var text = this.$refs.editorComponentRef.getText()

                //
                // there may be a problem here - we have to make sure that we saved
                // the correct code_id which is supposed to be the parent code id, so we
                // have to make sure that we save it every time we save code
                //
                this.save( this.base_component_id, this.code_id, text )
                //alert(1)
            },

            chooseCode: function() {
                this.code_width = "95%"
                this.code_shown = true

                this.app_width = "0%"
                this.app_shown = false

                mm.load_app( this.base_component_id )
            },

            chooseBoth: function() {
                this.code_width = "63%"
                this.code_shown = true

                this.app_width = "33%"
                this.app_shown = true
            },

            copyAppMethod: function(x) {
                copyApp(x)
            }
            ,

           // ---------------------------------------------------------------
           //                           save
           //
           // This is called to save the currently edited code
           // ---------------------------------------------------------------
           save: async function( base_component_id, code_id, text ) {
               //alert("Saving " + code_id)
               //alert("Saving " + text)
               //alert(base_component_id)
               var results = await callApp(
               {
                   driver_name:     "appEditorV2SaveCode",
                   method_name:     "saveCode"
               },
                   {
                        base_component_id:      base_component_id,
                        code_id:                code_id,
                        code:                   text
                   })
               //alert("Saved " + text)

               //alert("Reloading 2: " + JSON.stringify(results,null,2))
               //alert("Reloading 2: " + JSON.stringify(mm.base_component_id,null,2))
               mm.load_app( mm.base_component_id )
           },

           // ---------------------------------------------------------------
           //                           load_app
           //
           // This loads the latest version of the code stream marked with
           // 'baseComponentId'
           // ---------------------------------------------------------------
           load_app: async function ( baseComponentId ) {
               //
               // set up vars
               //
               mm.app_loaded            = false
               mm.base_component_id     = baseComponentId
               mm.app_component_name    = null
               mm.card_id               = cardId

               //
               // read the code for the component that we are editing
               //
               var sql =    "select  id, cast(code as text)  as  code, editors  from  system_code  where " +
                            "        component_type = 'app' and base_component_id = '" + baseComponentId + "'" +
                            "        and code_tag = 'LATEST' "

               var results = await callApp(
                   {
                        driver_name:    "systemFunctions2",
                        method_name:    "sql"
                   }
                   ,
                   {
                       sql: sql
                   })

               if (results) {
                   //alert(JSON.stringify(results,null,2))
                   if (results.length > 0) {
                       var editors2 = results[0].editors
                       var newEditor = null
                       if (editors2) {
                            var edd = eval("(" + editors2 + ")")
                            newEditor = edd[0]
                       }
                       var code = results[0].code
                       var codeId = results[0].id
                       //alert(code)
                       if (mm.editor_loaded && (mm.code != code)) {
                            //alert("changed: " + code)
                            this.$refs.editorComponentRef.setText(code)
                       }
                       mm.code = code
                       mm.code_id = codeId
                       //alert(JSON.stringify(1,null,2))

                       if (!mm.editor_loaded) {
                            var editorName = "editor_component"
                            if (newEditor) {
                                 editorName = newEditor
                            }

                            await load(editorName,{text: code})
                            mm.editor_loaded = true
                            mm.editor_component = editorName
                       }

                   }

                   setTimeout(async function() {
                       var results = await callApp( {code_id:    codeId },{})
                       mm.app_loaded = true
                       mm.baseComponentId = baseComponentId
                       mm.app_component_name = baseComponentId
                       //alert(results.name + " loaded")
                   },200)
               }

               }

       },

       mounted: async function () {
           mm = this
           //alert(argBaseComponentId)
           if (argBaseComponentId) {
                this.load_app(argBaseComponentId)
            } else {
                var result = await callApp( {
                                        driver_name:  "systemFunctions",
                                        method_name:  "get_apps_list"  } ,{})

                mm.apps = result
            }
       }
       })
       return {name: "app_editor"}

}
<commit_msg>better text<commit_after>async function(args) {
/*
created_timestamp(-1)
base_component_id("app_editor_3")
is_app(true)
display_name("Editor App V3")
description("This will return the editor app V3")
visibility("PUBLIC")
logo_url("https://2.bp.blogspot.com/-6Hdixw3dFxk/WfSQOnB9lDI/AAAAAAAAFFc/84DRGgcwOpYBOgknkHQ-qmgxvFv1D-iHACLcBGAs/s1600/BracketsDarks.PNG")
load_once_from_file(true)
*/

    var argBaseComponentId = args.base_component_id
    var cardId = args.card_id

    var mm = null
    Vue.component("app_editor_3",
    {
      template: `

                    App Editor V3

{{app_component_name?app_component_name.substring(0,30):""}}{{(app_component_name && ((app_component_name.length > 30))?"...":"")}}

                            <button  type=button class='btn btn-primary'      v-on:click='chooseApp()'  >App</button>
                            <button  type=button class=' btn btn-secondary'   v-on:click='chooseCode()' >Code</button>
                            <button  type=button class=' btn btn-info'        v-on:click='chooseBoth()' >Both</button>
                            <button  type=button class=' btn btn-secondary'   v-on:click='copyAppMethod(base_component_id)' >Copy app</button>
                            <button  type=button class=' btn btn-info'        v-on:click='prepareApp(card_id, \"appEmbed\", {base_component_id: base_component_id})' >Embed app</button>

                      Select an application to edit

                    <select class="custom-select" v-model="selected_app" v-bind:onchange='load_app(selected_app)'>
                      <option value='' selected></option>
                      <option v-for='app in apps'
                              v-bind:value="app.base_component_id"
                              >{{app.display_name}}</option>
                    </select>

                      <component  v-bind:is="editor_component" v-if="editor_loaded" ref="editorComponentRef">
                                      <button v-bind:style="'visibility: ' + ((app_shown && code_shown)?'':'hidden')"
                                              slot-scope="editor_component"
                                              v-on:click='save(base_component_id, code_id, editor_component.text2)'
                                              type="button" class="btn btn-primary">

                                                  Update App
                                     </button>
                      </component>

                      <component  v-bind:is="app_component_name" v-if="app_loaded">
                        APP HERE
                      </component>

       `
       ,
       data: function() {
           return {
               editor_loaded:       false,
               selected_app:        null,
               editor_component:    null,
               app_loaded:          false,
               apps:               [],
               app_component_name:  null,
               base_component_id:   null,
               code_id:            "...",
               version: 0,
               card_id: null,
               app_width:           "33%",
               code_width:          "63%",
               app_shown:           true,
               code_shown:          true
           }
       }
       ,
       methods: {
            // ---------------------------------------------------------------
            //                         chooseApp
            //
            // This is called when the end user selects an app from the menu
            // ---------------------------------------------------------------
            chooseApp: function() {
                this.code_width = "0%"
                this.code_shown = false

                this.app_width = "95%"
                this.app_shown = true

                var text = this.$refs.editorComponentRef.getText()

                //
                // there may be a problem here - we have to make sure that we saved
                // the correct code_id which is supposed to be the parent code id, so we
                // have to make sure that we save it every time we save code
                //
                this.save( this.base_component_id, this.code_id, text )
                //alert(1)
            },

            chooseCode: function() {
                this.code_width = "95%"
                this.code_shown = true

                this.app_width = "0%"
                this.app_shown = false

                mm.load_app( this.base_component_id )
            },

            chooseBoth: function() {
                this.code_width = "63%"
                this.code_shown = true

                this.app_width = "33%"
                this.app_shown = true
            },

            copyAppMethod: function(x) {
                copyApp(x)
            }
            ,

           // ---------------------------------------------------------------
           //                           save
           //
           // This is called to save the currently edited code
           // ---------------------------------------------------------------
           save: async function( base_component_id, code_id, text ) {
               //alert("Saving " + code_id)
               //alert("Saving " + text)
               //alert(base_component_id)
               var results = await callApp(
               {
                   driver_name:     "appEditorV2SaveCode",
                   method_name:     "saveCode"
               },
                   {
                        base_component_id:      base_component_id,
                        code_id:                code_id,
                        code:                   text
                   })
               //alert("Saved " + text)

               //alert("Reloading 2: " + JSON.stringify(results,null,2))
               //alert("Reloading 2: " + JSON.stringify(mm.base_component_id,null,2))
               mm.load_app( mm.base_component_id )
           },

           // ---------------------------------------------------------------
           //                           load_app
           //
           // This loads the latest version of the code stream marked with
           // 'baseComponentId'
           // ---------------------------------------------------------------
           load_app: async function ( baseComponentId ) {
               if (baseComponentId == "") {
                    return
               }
               //
               // set up vars
               //
               mm.app_loaded            = false
               mm.base_component_id     = baseComponentId
               mm.app_component_name    = null
               mm.card_id               = cardId

               //
               // read the code for the component that we are editing
               //
               var sql =    "select  id, cast(code as text)  as  code, editors  from  system_code  where " +
                            "        component_type = 'app' and base_component_id = '" + baseComponentId + "'" +
                            "        and code_tag = 'LATEST' "

               var results = await callApp(
                   {
                        driver_name:    "systemFunctions2",
                        method_name:    "sql"
                   }
                   ,
                   {
                       sql: sql
                   })

               if (results) {
                   //alert(JSON.stringify(results,null,2))
                   if (results.length > 0) {
                       var editors2 = results[0].editors
                       var newEditor = null
                       if (editors2) {
                            var edd = eval("(" + editors2 + ")")
                            newEditor = edd[0]
                       }
                       var code = results[0].code
                       var codeId = results[0].id
                       //alert(code)
                       if (mm.editor_loaded && (mm.code != code)) {
                            //alert("changed: " + code)
                            this.$refs.editorComponentRef.setText(code)
                       }
                       mm.code = code
                       mm.code_id = codeId
                       //alert(JSON.stringify(1,null,2))

                       if (!mm.editor_loaded) {
                            var editorName = "editor_component"
                            if (newEditor) {
                                 editorName = newEditor
                            }

                            await load(editorName,{text: code})
                            mm.editor_loaded = true
                            mm.editor_component = editorName
                       }

                   }

                   setTimeout(async function() {
                       var results = await callApp( {code_id:    codeId },{})
                       mm.app_loaded = true
                       mm.baseComponentId = baseComponentId
                       mm.app_component_name = baseComponentId
                       //alert(results.name + " loaded")
                   },200)
               }

               }

       },

       mounted: async function () {
           mm = this
           //alert(argBaseComponentId)
           if (argBaseComponentId) {
                this.load_app(argBaseComponentId)
            } else {
                var result = await callApp( {
                                        driver_name:  "systemFunctions",
                                        method_name:  "get_apps_list"  } ,{})

                mm.apps = result
            }
       }
       })
       return {name: "app_editor"}

}
<|endoftext|>


<commit_before>/*
 * Licensed to Cloudkick, Inc ('Cloudkick') under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * Cloudkick licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var sys = require('sys');
var fs = require('fs');
var path = require('path');
var http = require('http');
var crypto = require('crypto');
var pumpfile = require('util/http_pumpfile');
var client_config = require('util/config');
var misc = require('util/misc');
var spinner = require('util/spinner');
var manifest = require('manifest/index');
var MANIFEST_FILENAME = require('manifest/constants').MANIFEST_FILENAME;
var async = require('extern/async');

var config = {
  short_description: 'Upload an application bundle.',
  long_description: 'Upload an application bundle to a remote server.',
  required_arguments: [],
  optional_arguments: [['version', 'The bundle version to upload, defaults to the newest available']],
  switches: []
};

function handle_command(args) {
  var manifest_path = path.join(process.cwd(), MANIFEST_FILENAME);
  var bundledir = path.join(process.cwd(), client_config.get().temp_directory);
  var version = args.version;
  var bundlename;
  var fpath;
  var sha1;
  var size = 0;

  async.series([
    function(callback) {
      // If no version was specified then look up the most recently modified bundle
      if (!version) {
        fs.readdir(bundledir, function(err, files) {
          var msg;

          if (err) {
            msg = "Unable to read " + bundledir + ", have you created a bundle yet?";
            return callback(new Error(msg));
          }

          var newestfile;
          var newestmtime;

          async.forEach(files, function(file, callback) {
            fs.stat(path.join(bundledir, file), function(err, stats) {
              if (!err && stats.isFile() && (!newestmtime || stats.mtime > newestmtime)) {
                newestmtime = stats.mtime;
                newestfile = file;
              }
              return callback();
            });
          },
          function(err) {
            if (!err && !newestfile) {
              msg = "No bundles found in " + bundledir + " have you created one yet?";
              err = new Error(msg);
            }
            else {
              fpath = path.join(bundledir, newestfile);
            }
            return callback(err);
          });
        });
      }

      // If a version was specified, make sure it exists
      else {
        fpath = path.join(bundledir, version + '.tar.gz');
        fs.stat(fpath, function(err, stats) {
          if (err || !stats.isFile()) {
            err = new Error("Specified version does not exist.");
          }
          return callback(err);
        });
      }
    },

    // Validate the manifest and get the bundle name
    function(callback) {
      manifest.validate_manifest(manifest_path, function(err, app_manifest) {
        if (!err) {
          bundlename = misc.get_valid_bundle_name(app_manifest.name);
        }
        return callback(err);
      });
    },

    // Calculate the SHA1
    function(callback) {
      sha1 = crypto.createHash('sha1');
      var fstream = fs.createReadStream(fpath, {'bufferSize': client_config.get().fileread_buffer_size});
      var errstate = false;

      fstream.on('data', function(data) {
        sha1.update(data);
        size += data.length;
      });

      fstream.on('error', function(err) {
        errstate = true;
        return callback(new Error("Error reading bundle file."));
      });

      fstream.on('end', function() {
        if (!errstate) {
          return callback();
        }
      });
    },

    function(callback) {
      var remotepath = path.join('/', 'bundles', bundlename, path.basename(fpath));
      var pbar = spinner.percentbar("Uploading " + path.basename(fpath), size);
      var completed = false;

      pbar.start();
      // TODO: Allow custom remotes
      var client = http.createClient(8010, 'localhost');

      client.on('error', function(err) {
        completed = true;
        return callback(new Error("A connection error occurred"));
      });

      var bytes = 0;

      var request = client.request('PUT', remotepath, {
        'host': 'localhost',
        'content-length': size,
        'transfer-encoding': 'chunked',
        'x-content-sha1': sha1.digest('base64')
      });

      var fstream = fs.createReadStream(fpath, {'bufferSize': client_config.get().fileread_buffer_size});

      pumpfile.pumpfileout(fpath, request,
        function(bytes) {
          if (!completed) {
            pbar.tick(bytes);
          }
        },
        function(err) {
          if (!completed) {
            completed = true;

            if (err) {
              return callback(new Error("Error uploading bundle file"));
            }
            pbar.end();
            sys.puts("Waiting for response...");
            request.on('response', function(response) {
              if (response.statusCode === 204) {
                return callback();
              }
              var chunks = [];

              response.on('data', function(data) {
                chunks.push(data);
              });

              response.on('end', function() {
                try {
                  var err = JSON.parse(chunks.join(''));
                  return callback(new Error(err.message));
                }
                catch (err2) {
                  return callback(new Error("Unexpected response from agent"));
                }
              });
            });
          }
        }
      );
    }
  ],
  function(err) {
    if (err) {
      sys.puts("Error: " + err.message);
    }
    else {
      sys.puts("Upload Successful");
    }
  });
}

exports.config = config;
exports.handle_command = handle_command;
<commit_msg>Fix cast temp directory path<commit_after>/*
 * Licensed to Cloudkick, Inc ('Cloudkick') under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * Cloudkick licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var sys = require('sys');
var fs = require('fs');
var path = require('path');
var http = require('http');
var crypto = require('crypto');
var pumpfile = require('util/http_pumpfile');
var client_config = require('util/config');
var dotfiles = require('util/client_dotfiles');
var misc = require('util/misc');
var spinner = require('util/spinner');
var manifest = require('manifest/index');
var MANIFEST_FILENAME = require('manifest/constants').MANIFEST_FILENAME;
var async = require('extern/async');

var config = {
  short_description: 'Upload an application bundle.',
  long_description: 'Upload an application bundle to a remote server.',
  required_arguments: [],
  optional_arguments: [['version', 'The bundle version to upload, defaults to the newest available']],
  switches: []
};

function handle_command(args) {
  var manifest_path = path.join(process.cwd(), MANIFEST_FILENAME);
  var bundledir = path.join(dotfiles.dot_cast_project_path(process.cwd()), 'tmp');
  var version = args.version;
  var bundlename;
  var fpath;
  var sha1;
  var size = 0;

  async.series([
    function(callback) {
      // If no version was specified then look up the most recently modified bundle
      if (!version) {
        fs.readdir(bundledir, function(err, files) {
          var msg;

          if (err) {
            msg = "Unable to read " + bundledir + ", have you created a bundle yet?";
            return callback(new Error(msg));
          }

          var newestfile;
          var newestmtime;

          async.forEach(files, function(file, callback) {
            fs.stat(path.join(bundledir, file), function(err, stats) {
              if (!err && stats.isFile() && (!newestmtime || stats.mtime > newestmtime)) {
                newestmtime = stats.mtime;
                newestfile = file;
              }
              return callback();
            });
          },
          function(err) {
            if (!err && !newestfile) {
              msg = "No bundles found in " + bundledir + " have you created one yet?";
              err = new Error(msg);
            }
            else {
              fpath = path.join(bundledir, newestfile);
            }
            return callback(err);
          });
        });
      }

      // If a version was specified, make sure it exists
      else {
        fpath = path.join(bundledir, version + '.tar.gz');
        fs.stat(fpath, function(err, stats) {
          if (err || !stats.isFile()) {
            err = new Error("Specified version does not exist.");
          }
          return callback(err);
        });
      }
    },

    // Validate the manifest and get the bundle name
    function(callback) {
      manifest.validate_manifest(manifest_path, function(err, app_manifest) {
        if (!err) {
          bundlename = misc.get_valid_bundle_name(app_manifest.name);
        }
        return callback(err);
      });
    },

    // Calculate the SHA1
    function(callback) {
      sha1 = crypto.createHash('sha1');
      var fstream = fs.createReadStream(fpath, {'bufferSize': client_config.get().fileread_buffer_size});
      var errstate = false;

      fstream.on('data', function(data) {
        sha1.update(data);
        size += data.length;
      });

      fstream.on('error', function(err) {
        errstate = true;
        return callback(new Error("Error reading bundle file."));
      });

      fstream.on('end', function() {
        if (!errstate) {
          return callback();
        }
      });
    },

    function(callback) {
      var remotepath = path.join('/', 'bundles', bundlename, path.basename(fpath));
      var pbar = spinner.percentbar("Uploading " + path.basename(fpath), size);
      var completed = false;

      pbar.start();
      // TODO: Allow custom remotes
      var client = http.createClient(8010, 'localhost');

      client.on('error', function(err) {
        completed = true;
        return callback(new Error("A connection error occurred"));
      });

      var bytes = 0;

      var request = client.request('PUT', remotepath, {
        'host': 'localhost',
        'content-length': size,
        'transfer-encoding': 'chunked',
        'x-content-sha1': sha1.digest('base64')
      });

      var fstream = fs.createReadStream(fpath, {'bufferSize': client_config.get().fileread_buffer_size});

      pumpfile.pumpfileout(fpath, request,
        function(bytes) {
          if (!completed) {
            pbar.tick(bytes);
          }
        },
        function(err) {
          if (!completed) {
            completed = true;

            if (err) {
              return callback(new Error("Error uploading bundle file"));
            }
            pbar.end();
            sys.puts("Waiting for response...");
            request.on('response', function(response) {
              if (response.statusCode === 204) {
                return callback();
              }
              var chunks = [];

              response.on('data', function(data) {
                chunks.push(data);
              });

              response.on('end', function() {
                try {
                  var err = JSON.parse(chunks.join(''));
                  return callback(new Error(err.message));
                }
                catch (err2) {
                  return callback(new Error("Unexpected response from agent"));
                }
              });
            });
          }
        }
      );
    }
  ],
  function(err) {
    if (err) {
      sys.puts("Error: " + err.message);
    }
    else {
      sys.puts("Upload Successful");
    }
  });
}

exports.config = config;
exports.handle_command = handle_command;
<|endoftext|>