<commit_before>const { expect } = require('chai');
const path = require('path');
const fs = require('fs');
const vm = require('vm');

/*
 * We are testing autoloader component here
 * cannot use the autoloader itself to load classes! :)
 */
const Namespace = require('../src/Namespace');
const ClassLoader = require('../src/ClassLoader');
const ClassNotFoundException = require('../src/Exception/ClassNotFoundException');

describe('[Autoloader] Namespace', function () {
    afterEach(() => {
        ClassLoader.clearCache(__jymfony.Platform.isWindows() ? 'C:\\var\\node\\foo_vendor\\' : '/var/node/foo_vendor');
    });

    it('constructs as a Proxy', () => {
        /*
         * ES6 Proxies are transparent virtualized objects, so
         * it is impossible to know whether an object is a
         * proxy or not, we just check that is not a Namespace
         */

        const ns = new Namespace({});
        expect(ns).not.to.be.instanceof(Namespace);
        expect(ns.__namespace).to.be.instanceof(Namespace);
    });

    it('returns undefined if a symbol is requested', () => {
        const ns = new Namespace({});

        expect(ns[Symbol.iterator]).to.be.undefined;
    });

    it('returns undefined if namespace is not found', () => {
        const finder = {
            find: () => {
                const e = new Error();
                e.code = 'ENOENT';
            },
        };

        const ns = new Namespace({ finder: finder });
        const subns = ns.NotValid;

        expect(subns).to.be.undefined;
    });

    it('throws if namespace is not found and debug is enabled', () => {
        const finder = {
            find: () => {
                const e = new Error();
                e.code = 'ENOENT';
            },
        };

        const ns = new Namespace({ finder: finder });
        const subns = ns.NotValid;

        expect(subns).to.be.undefined;
    });

    it('throws if is not a constructor and debug is enabled', () => {
        const req = (module) => {
            if ('path' === module || 'vm' === module) {
                return require(module);
            }
        };
        req.cache = {
            '/var/node/foo_vendor/FooClass.js': {},
        };
        req.resolve = () => {
            return '/var/node/foo_vendor/FooClass.js';
        };

        const finder = {
            find: (dir, name) => {
                expect(name).to.be.equal('FooClass');
                return {
                    filename: '/var/node/foo_vendor/FooClass.js',
                    directory: false,
                };
            },
            load: (fn) => {
                expect(fn).to.be.equal(__jymfony.Platform.isWindows() ? 'C:\\var\\node\\foo_vendor\\FooClass.js' : '/var/node/foo_vendor/FooClass.js');
                return '';
            },
        };

        const ns = new Namespace({
            classLoader: new ClassLoader(finder, path, vm),
            debug: true,
            finder: finder,
        }, 'Foo', [
            '/var/node/foo_vendor',
        ], req);

        expect(() => {
            const class_ = ns.FooClass;
            expect(class_).to.be.undefined;
        }).to.throw(ClassNotFoundException);
    });

    it('object can be set', () => {
        const ns = new Namespace({});
        ns.subNs = {
            foo: 'bar',
        };

        expect(ns.subNs).to.be.deep.equal({
            foo: 'bar',
        });
    });

    it('searches in all base dirs', () => {
        const finder = {
            find: (dir, name) => {
                switch (dir) {
                    case '/var/node/vendor1/':
                        return undefined;

                    case '/var/node/foo_vendor/':
                        expect(name).to.be.equal('FooClass');
                        return {
                            filename: '/var/node/foo_vendor/FooClass.js',
                            directory: false,
                        };

                    default:
                        throw new Error('Unexpected argument');
                }
            },
            load: (fn) => {
                expect(fn).to.be.equal(__jymfony.Platform.isWindows() ? 'C:\\var\\node\\foo_vendor\\FooClass.js' : '/var/node/foo_vendor/FooClass.js');
                return 'module.exports = function () { };';
            },
        };

        const req = (module) => {
            if ('path' === module || 'vm' === module) {
                return require(module);
            }
        };
        req.cache = {
            '/var/node/foo_vendor/FooClass.js': {},
        };
        req.resolve = () => {
            return '/var/node/foo_vendor/FooClass.js';
        };

        const ns = new Namespace({
            classLoader: new ClassLoader(finder, path, vm),
            finder: finder,
        }, 'Foo', [], req);

        ns.__namespace.addDirectory('/var/node/vendor1/');
        ns.__namespace.addDirectory('/var/node/foo_vendor/');

        const func = ns.FooClass;
        expect(func).to.be.instanceOf(Function);
    });

    it('injects reflection metadata', () => {
        const finder = {
            find: (dir, name) => {
                if ('/var/node/foo_vendor/' === dir) {
                    expect(name).to.be.equal('FooClass');
                    return {
                        filename: '/var/node/foo_vendor/FooClass.js',
                        directory: false,
                    };
                }
                throw new Error('Unexpected argument');

            },
            load: fn => {
                expect(fn).to.be.equal(__jymfony.Platform.isWindows() ? 'C:\\var\\node\\foo_vendor\\FooClass.js' : '/var/node/foo_vendor/FooClass.js');
                return 'module.exports = class FooClass {}';
            },
        };

        const req = (module) => {
            if ('path' === module || 'vm' === module) {
                return require(module);
            }
        };
        req.cache = {
            '/var/node/foo_vendor/FooClass.js': {},
        };
        req.resolve = () => {
            return '/var/node/foo_vendor/FooClass.js';
        };

        const ns = new Namespace({
            classLoader: new ClassLoader(finder, path, vm),
            finder: finder,
        }, 'Foo', [ '/var/node/foo_vendor/' ], req);

        const func = ns.FooClass;

        expect(func).to.be.instanceOf(Function);
        expect(func[Symbol.reflection]).to.have.property('filename').that.equals('/var/node/foo_vendor/FooClass.js');
        expect(func[Symbol.reflection]).to.have.property('fqcn').that.equals('Foo.FooClass');
        expect(func[Symbol.reflection]).to.have.property('constructor');
        expect(func[Symbol.reflection]).to.have.property('namespace');
    });

    it('calls __construct on new if defined', () => {
        const finder = {
            find: (dir, name) => {
                if ('/var/node/foo_vendor/' === dir) {
                    expect(name).to.be.equal('FooClass');
                    return {
                        filename: '/var/node/foo_vendor/FooClass.js',
                        directory: false,
                    };
                }
                throw new Error('Unexpected argument');

            },
            load: fn => {
                expect(fn).to.be.equal(__jymfony.Platform.isWindows() ? 'C:\\var\\node\\foo_vendor\\FooClass.js' : '/var/node/foo_vendor/FooClass.js');
                return `module.exports = class FooClass {
                    __construct(arg) {
                        this.constructCalled = arg;
                    }
                };`;
            },
        };

        const req = (module) => {
            if ('path' === module || 'vm' === module) {
                return require(module);
            }
        };
        req.cache = {
            '/var/node/foo_vendor/FooClass.js': {},
        };
        req.resolve = () => {
            return '/var/node/foo_vendor/FooClass.js';
        };

        const ns = new Namespace({
            classLoader: new ClassLoader(finder, path, vm),
            finder: finder,
        }, 'Foo', [ '/var/node/foo_vendor/' ], req);

        const obj = new ns.FooClass('foobar');
        expect(obj.constructCalled).to.be.equal('foobar');
    });

    it('calls __construct on new if defined', () => {
        const finder = {
            find: (dir, name) => {
                if ('/var/node/foo_vendor/' === dir) {
                    if ('FooClass' === name) {
                        return {
                            filename: '/var/node/foo_vendor/FooClass.js',
                            directory: false,
                        };
                    } else if ('BarClass' === name) {
                        return {
                            filename: '/var/node/foo_vendor/BarClass.js',
                            directory: false,
                        };
                    }
                }

                throw new Error('Unexpected argument');
            },
            load: fn => {
                if ((__jymfony.Platform.isWindows() ? 'C:\\var\\node\\foo_vendor\\FooClass.js' : '/var/node/foo_vendor/FooClass.js') === fn) {
                    return `module.exports = class FooClass extends __ns.BarClass {
                        __construct(arg) {
                            this.constructCalled = arg;
                        }
                    }`;
                } else if ((__jymfony.Platform.isWindows() ? 'C:\\var\\node\\foo_vendor\\BarClass.js' : '/var/node/foo_vendor/BarClass.js') === fn) {
                    return `module.exports = class BarClass {
                        __construct(arg) {
                            this.superCalled = arg;
                        }
                    };`;
                }
            },
        };

        const req = (module) => {
            if ('path' === module || 'vm' === module) {
                return require(module);
            }
        };
        req.cache = {
            '/var/node/foo_vendor/BarClass.js': {},
            '/var/node/foo_vendor/FooClass.js': {},
        };
        req.resolve = (module) => module;

        const ns = new Namespace({
            classLoader: new ClassLoader(finder, path, vm),
            finder: finder,
        }, 'Foo', [ '/var/node/foo_vendor/' ], req);

        try {
            global.__ns = ns;

            const obj = new ns.FooClass('foobar');
            expect(obj.constructCalled).to.be.equal('foobar');
            expect(obj.superCalled).to.be.undefined;
        } finally {
            delete global.__ns;
        }
    });

    it('resolves circular requirements', () => {
        const finder = {
            find: (dir, name) => {
                if ('FooClass' === name) {
                    return {
                        filename: path.join(__dirname, '..', 'fixtures', 'FooClass.js'),
                        directory: false,
                    };
                } else if ('BarClass' === name) {
                    return {
                        filename: path.join(__dirname, '..', 'fixtures', 'BarClass.js'),
                        directory: false,
                    };
                }

                throw new Error('Unexpected argument');
            },
            load: fn => {
                return fs.readFileSync(fn, 'utf-8');
            },
        };

        const ns = new Namespace({
            classLoader: new ClassLoader(finder, path, vm),
            finder: finder,
        }, 'Foo', path.join(__dirname, '..', 'fixtures'), __jymfony.autoload.classLoader._internalRequire);
        try {
            global.Foo = ns;

            const foo = new ns.FooClass();
            const bar = foo.bar;

            expect(bar).to.be.instanceOf(ns.BarClass);
            expect(foo).to.be.instanceOf(ns.FooClass);
            expect(ns.FooClass.HELLO).to.be.equal('Hello, world!');
        } finally {
            delete global.Foo;
        }
    });
});
<commit_msg>enable ci on github actions<commit_after>const { expect } = require('chai');
const path = require('path');
const fs = require('fs');
const vm = require('vm');

const cwdOSRoot = path.parse(process.cwd()).root.toUpperCase();

/*
 * We are testing autoloader component here
 * cannot use the autoloader itself to load classes! :)
 */
const Namespace = require('../src/Namespace');
const ClassLoader = require('../src/ClassLoader');
const ClassNotFoundException = require('../src/Exception/ClassNotFoundException');

describe('[Autoloader] Namespace', function () {
    afterEach(() => {
        ClassLoader.clearCache(__jymfony.Platform.isWindows() ? cwdOSRoot + 'var\\node\\foo_vendor\\' : '/var/node/foo_vendor');
    });

    it('constructs as a Proxy', () => {
        /*
         * ES6 Proxies are transparent virtualized objects, so
         * it is impossible to know whether an object is a
         * proxy or not, we just check that is not a Namespace
         */

        const ns = new Namespace({});
        expect(ns).not.to.be.instanceof(Namespace);
        expect(ns.__namespace).to.be.instanceof(Namespace);
    });

    it('returns undefined if a symbol is requested', () => {
        const ns = new Namespace({});

        expect(ns[Symbol.iterator]).to.be.undefined;
    });

    it('returns undefined if namespace is not found', () => {
        const finder = {
            find: () => {
                const e = new Error();
                e.code = 'ENOENT';
            },
        };

        const ns = new Namespace({ finder: finder });
        const subns = ns.NotValid;

        expect(subns).to.be.undefined;
    });

    it('throws if namespace is not found and debug is enabled', () => {
        const finder = {
            find: () => {
                const e = new Error();
                e.code = 'ENOENT';
            },
        };

        const ns = new Namespace({ finder: finder });
        const subns = ns.NotValid;

        expect(subns).to.be.undefined;
    });

    it('throws if is not a constructor and debug is enabled', () => {
        const req = (module) => {
            if ('path' === module || 'vm' === module) {
                return require(module);
            }
        };
        req.cache = {
            '/var/node/foo_vendor/FooClass.js': {},
        };
        req.resolve = () => {
            return '/var/node/foo_vendor/FooClass.js';
        };

        const finder = {
            find: (dir, name) => {
                expect(name).to.be.equal('FooClass');
                return {
                    filename: '/var/node/foo_vendor/FooClass.js',
                    directory: false,
                };
            },
            load: (fn) => {
                expect(fn).to.be.equal(__jymfony.Platform.isWindows() ? cwdOSRoot + 'var\\node\\foo_vendor\\FooClass.js' : '/var/node/foo_vendor/FooClass.js');
                return '';
            },
        };

        const ns = new Namespace({
            classLoader: new ClassLoader(finder, path, vm),
            debug: true,
            finder: finder,
        }, 'Foo', [
            '/var/node/foo_vendor',
        ], req);

        expect(() => {
            const class_ = ns.FooClass;
            expect(class_).to.be.undefined;
        }).to.throw(ClassNotFoundException);
    });

    it('object can be set', () => {
        const ns = new Namespace({});
        ns.subNs = {
            foo: 'bar',
        };

        expect(ns.subNs).to.be.deep.equal({
            foo: 'bar',
        });
    });

    it('searches in all base dirs', () => {
        const finder = {
            find: (dir, name) => {
                switch (dir) {
                    case '/var/node/vendor1/':
                        return undefined;

                    case '/var/node/foo_vendor/':
                        expect(name).to.be.equal('FooClass');
                        return {
                            filename: '/var/node/foo_vendor/FooClass.js',
                            directory: false,
                        };

                    default:
                        throw new Error('Unexpected argument');
                }
            },
            load: (fn) => {
                expect(fn).to.be.equal(__jymfony.Platform.isWindows() ? cwdOSRoot + 'var\\node\\foo_vendor\\FooClass.js' : '/var/node/foo_vendor/FooClass.js');
                return 'module.exports = function () { };';
            },
        };

        const req = (module) => {
            if ('path' === module || 'vm' === module) {
                return require(module);
            }
        };
        req.cache = {
            '/var/node/foo_vendor/FooClass.js': {},
        };
        req.resolve = () => {
            return '/var/node/foo_vendor/FooClass.js';
        };

        const ns = new Namespace({
            classLoader: new ClassLoader(finder, path, vm),
            finder: finder,
        }, 'Foo', [], req);

        ns.__namespace.addDirectory('/var/node/vendor1/');
        ns.__namespace.addDirectory('/var/node/foo_vendor/');

        const func = ns.FooClass;
        expect(func).to.be.instanceOf(Function);
    });

    it('injects reflection metadata', () => {
        const finder = {
            find: (dir, name) => {
                if ('/var/node/foo_vendor/' === dir) {
                    expect(name).to.be.equal('FooClass');
                    return {
                        filename: '/var/node/foo_vendor/FooClass.js',
                        directory: false,
                    };
                }
                throw new Error('Unexpected argument');

            },
            load: fn => {
                expect(fn).to.be.equal(__jymfony.Platform.isWindows() ? cwdOSRoot + 'var\\node\\foo_vendor\\FooClass.js' : '/var/node/foo_vendor/FooClass.js');
                return 'module.exports = class FooClass {}';
            },
        };

        const req = (module) => {
            if ('path' === module || 'vm' === module) {
                return require(module);
            }
        };
        req.cache = {
            '/var/node/foo_vendor/FooClass.js': {},
        };
        req.resolve = () => {
            return '/var/node/foo_vendor/FooClass.js';
        };

        const ns = new Namespace({
            classLoader: new ClassLoader(finder, path, vm),
            finder: finder,
        }, 'Foo', [ '/var/node/foo_vendor/' ], req);

        const func = ns.FooClass;

        expect(func).to.be.instanceOf(Function);
        expect(func[Symbol.reflection]).to.have.property('filename').that.equals('/var/node/foo_vendor/FooClass.js');
        expect(func[Symbol.reflection]).to.have.property('fqcn').that.equals('Foo.FooClass');
        expect(func[Symbol.reflection]).to.have.property('constructor');
        expect(func[Symbol.reflection]).to.have.property('namespace');
    });

    it('calls __construct on new if defined', () => {
        const finder = {
            find: (dir, name) => {
                if ('/var/node/foo_vendor/' === dir) {
                    expect(name).to.be.equal('FooClass');
                    return {
                        filename: '/var/node/foo_vendor/FooClass.js',
                        directory: false,
                    };
                }
                throw new Error('Unexpected argument');

            },
            load: fn => {
                expect(fn).to.be.equal(__jymfony.Platform.isWindows() ? cwdOSRoot + 'var\\node\\foo_vendor\\FooClass.js' : '/var/node/foo_vendor/FooClass.js');
                return `module.exports = class FooClass {
                    __construct(arg) {
                        this.constructCalled = arg;
                    }
                };`;
            },
        };

        const req = (module) => {
            if ('path' === module || 'vm' === module) {
                return require(module);
            }
        };
        req.cache = {
            '/var/node/foo_vendor/FooClass.js': {},
        };
        req.resolve = () => {
            return '/var/node/foo_vendor/FooClass.js';
        };

        const ns = new Namespace({
            classLoader: new ClassLoader(finder, path, vm),
            finder: finder,
        }, 'Foo', [ '/var/node/foo_vendor/' ], req);

        const obj = new ns.FooClass('foobar');
        expect(obj.constructCalled).to.be.equal('foobar');
    });

    it('calls __construct on new if defined', () => {
        const finder = {
            find: (dir, name) => {
                if ('/var/node/foo_vendor/' === dir) {
                    if ('FooClass' === name) {
                        return {
                            filename: '/var/node/foo_vendor/FooClass.js',
                            directory: false,
                        };
                    } else if ('BarClass' === name) {
                        return {
                            filename: '/var/node/foo_vendor/BarClass.js',
                            directory: false,
                        };
                    }
                }

                throw new Error('Unexpected argument');
            },
            load: fn => {
                if ((__jymfony.Platform.isWindows() ? cwdOSRoot + 'var\\node\\foo_vendor\\FooClass.js' : '/var/node/foo_vendor/FooClass.js') === fn) {
                    return `module.exports = class FooClass extends __ns.BarClass {
                        __construct(arg) {
                            this.constructCalled = arg;
                        }
                    }`;
                } else if ((__jymfony.Platform.isWindows() ? cwdOSRoot + 'var\\node\\foo_vendor\\BarClass.js' : '/var/node/foo_vendor/BarClass.js') === fn) {
                    return `module.exports = class BarClass {
                        __construct(arg) {
                            this.superCalled = arg;
                        }
                    };`;
                }
            },
        };

        const req = (module) => {
            if ('path' === module || 'vm' === module) {
                return require(module);
            }
        };
        req.cache = {
            '/var/node/foo_vendor/BarClass.js': {},
            '/var/node/foo_vendor/FooClass.js': {},
        };
        req.resolve = (module) => module;

        const ns = new Namespace({
            classLoader: new ClassLoader(finder, path, vm),
            finder: finder,
        }, 'Foo', [ '/var/node/foo_vendor/' ], req);

        try {
            global.__ns = ns;

            const obj = new ns.FooClass('foobar');
            expect(obj.constructCalled).to.be.equal('foobar');
            expect(obj.superCalled).to.be.undefined;
        } finally {
            delete global.__ns;
        }
    });

    it('resolves circular requirements', () => {
        const finder = {
            find: (dir, name) => {
                if ('FooClass' === name) {
                    return {
                        filename: path.join(__dirname, '..', 'fixtures', 'FooClass.js'),
                        directory: false,
                    };
                } else if ('BarClass' === name) {
                    return {
                        filename: path.join(__dirname, '..', 'fixtures', 'BarClass.js'),
                        directory: false,
                    };
                }

                throw new Error('Unexpected argument');
            },
            load: fn => {
                return fs.readFileSync(fn, 'utf-8');
            },
        };

        const ns = new Namespace({
            classLoader: new ClassLoader(finder, path, vm),
            finder: finder,
        }, 'Foo', path.join(__dirname, '..', 'fixtures'), __jymfony.autoload.classLoader._internalRequire);
        try {
            global.Foo = ns;

            const foo = new ns.FooClass();
            const bar = foo.bar;

            expect(bar).to.be.instanceOf(ns.BarClass);
            expect(foo).to.be.instanceOf(ns.FooClass);
            expect(ns.FooClass.HELLO).to.be.equal('Hello, world!');
        } finally {
            delete global.Foo;
        }
    });
});
<|endoftext|>


<commit_before>/**
 * Copyright 2013-2020 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * Licensed 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.
 */
/* eslint-disable consistent-return */
const constants = require('../generator-constants');
const writeFiles = require('./files').writeFiles;
const utils = require('../utils');
const BaseBlueprintGenerator = require('../generator-base-blueprint');
const { isReservedTableName } = require('../../jdl/jhipster/reserved-keywords');

/* constants used throughout */
let useBlueprints;

module.exports = class extends BaseBlueprintGenerator {
    constructor(args, opts) {
        super(args, opts);
        utils.copyObjectProps(this, opts.context);
        this.jhipsterContext = opts.jhipsterContext || opts.context;

        this.testsNeedCsrf = ['uaa', 'oauth2', 'session'].includes(this.jhipsterContext.authenticationType);
        this.officialDatabaseType = constants.OFFICIAL_DATABASE_TYPE_NAMES[this.jhipsterContext.databaseType];

        useBlueprints = !this.fromBlueprint && this.instantiateBlueprints('entity-server', { context: opts.context });
    }

    // Public API method used by the getter and also by Blueprints
    _initializing() {
        return {
            setupConstants() {
                // Make constants available in templates
                this.LIQUIBASE_DTD_VERSION = constants.LIQUIBASE_DTD_VERSION;
            },
        };
    }

    get initializing() {
        if (useBlueprints) return;
        return this._initializing();
    }

    // Public API method used by the getter and also by Blueprints
    _default() {
        return super._missingPreDefault();
    }

    get default() {
        if (useBlueprints) return;
        return this._default();
    }

    // Public API method used by the getter and also by Blueprints
    _writing() {
        return { ...writeFiles(), ...super._missingPostWriting() };
    }

    get writing() {
        if (useBlueprints) return;
        return this._writing();
    }

    _preparing() {
        return {
            /**
             * Process json ignore references to prevent cyclic relationships.
             */
            processJsonIgnoreReferences() {
                this.relationships
                    .filter(relationship => relationship.relationshipOtherSideIgnore === undefined)
                    .forEach(relationship => {
                        relationship.ignoreOtherSideProperty = !relationship.embedded && !!relationship.otherEntity;
                    });
                this.relationshipsContainOtherSideIgnore = this.relationships.some(relationship => relationship.ignoreOtherSideProperty);
            },

            processJavaEntityImports() {
                this.importApiModelProperty =
                    this.relationships.some(relationship => relationship.javadoc) || this.fields.some(field => field.javadoc);
            },

            processUniqueEnums() {
                this.uniqueEnums = {};

                this.fields.forEach(field => {
                    if (
                        field.fieldIsEnum &&
                        (!this.uniqueEnums[field.fieldType] || (this.uniqueEnums[field.fieldType] && field.fieldValues.length !== 0))
                    ) {
                        this.uniqueEnums[field.fieldType] = field.fieldType;
                    }
                });
            },

            useMapsIdRelation() {
                const jpaDerivedRelation = this.relationships.find(rel => rel.useJPADerivedIdentifier === true);
                if (jpaDerivedRelation) {
                    this.isUsingMapsId = true;
                    this.mapsIdAssoc = jpaDerivedRelation;
                    this.hasOauthUser = this.mapsIdAssoc.otherEntityName === 'user' && this.authenticationType === 'oauth2';
                } else {
                    this.isUsingMapsId = false;
                    this.mapsIdAssoc = null;
                    this.hasOauthUser = false;
                }
            },

            processUniqueEntityTypes() {
                this.reactiveUniqueEntityTypes = new Set(this.reactiveEagerRelations.map(rel => rel.otherEntityNameCapitalized));
                this.reactiveUniqueEntityTypes.add(this.entityClass);
            },
        };
    }

    get preparing() {
        if (useBlueprints) return;
        return this._preparing();
    }

    /* Private methods used in templates */
    _getJoinColumnName(relationship) {
        if (relationship.useJPADerivedIdentifier === true) {
            return 'id';
        }
        return `${this.getColumnName(relationship.relationshipName)}_id`;
    }

    _generateSqlSafeName(name) {
        if (isReservedTableName(name, 'sql')) {
            return `e_${name}`;
        }
        return name;
    }
};
<commit_msg>Fix ignoreOtherSideProperty.<commit_after>/**
 * Copyright 2013-2020 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * Licensed 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.
 */
/* eslint-disable consistent-return */
const constants = require('../generator-constants');
const writeFiles = require('./files').writeFiles;
const utils = require('../utils');
const BaseBlueprintGenerator = require('../generator-base-blueprint');
const { isReservedTableName } = require('../../jdl/jhipster/reserved-keywords');

/* constants used throughout */
let useBlueprints;

module.exports = class extends BaseBlueprintGenerator {
    constructor(args, opts) {
        super(args, opts);
        utils.copyObjectProps(this, opts.context);
        this.jhipsterContext = opts.jhipsterContext || opts.context;

        this.testsNeedCsrf = ['uaa', 'oauth2', 'session'].includes(this.jhipsterContext.authenticationType);
        this.officialDatabaseType = constants.OFFICIAL_DATABASE_TYPE_NAMES[this.jhipsterContext.databaseType];

        useBlueprints = !this.fromBlueprint && this.instantiateBlueprints('entity-server', { context: opts.context });
    }

    // Public API method used by the getter and also by Blueprints
    _initializing() {
        return {
            setupConstants() {
                // Make constants available in templates
                this.LIQUIBASE_DTD_VERSION = constants.LIQUIBASE_DTD_VERSION;
            },
        };
    }

    get initializing() {
        if (useBlueprints) return;
        return this._initializing();
    }

    // Public API method used by the getter and also by Blueprints
    _default() {
        return super._missingPreDefault();
    }

    get default() {
        if (useBlueprints) return;
        return this._default();
    }

    // Public API method used by the getter and also by Blueprints
    _writing() {
        return { ...writeFiles(), ...super._missingPostWriting() };
    }

    get writing() {
        if (useBlueprints) return;
        return this._writing();
    }

    _preparing() {
        return {
            /**
             * Process json ignore references to prevent cyclic relationships.
             */
            processJsonIgnoreReferences() {
                this.relationships
                    .filter(relationship => relationship.relationshipOtherSideIgnore === undefined)
                    .forEach(relationship => {
                        relationship.ignoreOtherSideProperty =
                            !relationship.embedded && !!relationship.otherEntity && relationship.otherEntity.relationships.length > 0;
                    });
                this.relationshipsContainOtherSideIgnore = this.relationships.some(relationship => relationship.ignoreOtherSideProperty);
            },

            processJavaEntityImports() {
                this.importApiModelProperty =
                    this.relationships.some(relationship => relationship.javadoc) || this.fields.some(field => field.javadoc);
            },

            processUniqueEnums() {
                this.uniqueEnums = {};

                this.fields.forEach(field => {
                    if (
                        field.fieldIsEnum &&
                        (!this.uniqueEnums[field.fieldType] || (this.uniqueEnums[field.fieldType] && field.fieldValues.length !== 0))
                    ) {
                        this.uniqueEnums[field.fieldType] = field.fieldType;
                    }
                });
            },

            useMapsIdRelation() {
                const jpaDerivedRelation = this.relationships.find(rel => rel.useJPADerivedIdentifier === true);
                if (jpaDerivedRelation) {
                    this.isUsingMapsId = true;
                    this.mapsIdAssoc = jpaDerivedRelation;
                    this.hasOauthUser = this.mapsIdAssoc.otherEntityName === 'user' && this.authenticationType === 'oauth2';
                } else {
                    this.isUsingMapsId = false;
                    this.mapsIdAssoc = null;
                    this.hasOauthUser = false;
                }
            },

            processUniqueEntityTypes() {
                this.reactiveUniqueEntityTypes = new Set(this.reactiveEagerRelations.map(rel => rel.otherEntityNameCapitalized));
                this.reactiveUniqueEntityTypes.add(this.entityClass);
            },
        };
    }

    get preparing() {
        if (useBlueprints) return;
        return this._preparing();
    }

    /* Private methods used in templates */
    _getJoinColumnName(relationship) {
        if (relationship.useJPADerivedIdentifier === true) {
            return 'id';
        }
        return `${this.getColumnName(relationship.relationshipName)}_id`;
    }

    _generateSqlSafeName(name) {
        if (isReservedTableName(name, 'sql')) {
            return `e_${name}`;
        }
        return name;
    }
};
<|endoftext|>


<commit_before>function TrackSvgLayout(parent, trackDataList, args) {
	var _this = this;
	this.args = args;
	this.id = Math.round(Math.random()*10000000);
	this.trackDataList = trackDataList;

	this.trackSvgList =  new Array();
	this.swapHash = new Object();

	//default values
	this.height=25;

	if (args != null){
		if(args.width != null){
			this.width = args.width;
		}
		if(args.height != null){
			this.height = args.height;
		}
		if(args.position != null){
			this.position = args.position;
		}
		if(args.chromosome != null){
			this.chromosome = args.chromosome;
		}
		if(args.zoom != null){
			this.zoom = args.zoom;
		}
	}
	this._createPixelsbyBase();//create pixelByBase array

	this.pixelBase = this._getPixelsbyBase(this.zoom);

	this.svg = SVG.init(parent,{
		"width":this.width,
		"height":this.height
	});

	var mid = this.width/2;
	this.positionText = SVG.addChild(this.svg,"text",{
		"x":mid-30,
		"y":15,
		"fill":"green"
	});
	this.positionText.textContent = this.position;

	this.currentLine = SVG.addChild(this.svg,"line",{
			"x1":mid,
			"y1":this.height,
			"x2":mid,
			"y2":this.height,
			"stroke-width":"1",
			"stroke":"green"
	});

	this.onZoomChange = new Event();
	this.onMove = new Event();

	trackDataList.onAddTrack.addEventListener(function(sender,index){
		_this.draw(index);
	});
};

TrackSvgLayout.prototype.setHeight = function(height){
	this.height=height;
	this.svg.setAttribute("height",height);
};
TrackSvgLayout.prototype.setZoom = function(zoom){
	this.zoom=zoom;
	this.pixelBase = this._getPixelsbyBase(this.zoom);
	this.onZoomChange.notify();
};

TrackSvgLayout.prototype.draw = function(i){
	var _this = this;

	var trackData = this.trackDataList.getTrack(i);
	var trackSvg = new TrackSvg(this.svg,{
		position:this.position,
		zoom:this.zoom,
		pixelBase:this.pixelBase,
		id:trackData.id,
		width:this.width
	});

	//virtual window
	var halfVirtualWidth = _this.width*3/2;
	var virtualStart = parseInt(_this.position - halfVirtualWidth / _this.pixelBase);
	var vitualEnd = parseInt(_this.position + halfVirtualWidth / _this.pixelBase);
	trackData.retrieveData({chromosome:13,start:virtualStart,end:vitualEnd});

	//on zoom change set new virtual window and update track values
	this.onZoomChange.addEventListener(function(sender,data){
		trackSvg.zoom=_this.zoom;
		trackSvg.pixelBase=_this.pixelBase;
		while ( trackSvg.features.childNodes.length >= 1 )
	    {
			trackSvg.features.removeChild( trackSvg.features.firstChild );
	    }
		trackSvg.cache={};
		var virtualStart = parseInt(_this.position - halfVirtualWidth / _this.pixelBase);
		var vitualEnd = parseInt(_this.position + halfVirtualWidth / _this.pixelBase);
		trackData.retrieveData({chromosome:13,start:virtualStart,end:vitualEnd});
	});

	this.trackSvgList.push(trackSvg);
	this.swapHash[trackSvg.id] = {index:i,visible:true};
	trackSvg.setY(this.height);
	trackSvg.draw();

	//XXX se puede mover?
	$(trackSvg.upRect).bind("click",function(event){
		_this._reallocateAbove(this.parentNode.id);//"this" is the svg element
	});
	$(trackSvg.downRect).bind("click",function(event){
		_this._reallocateUnder(this.parentNode.id);//"this" is the svg element
	});
	$(trackSvg.hideRect).bind("click",function(event){
		_this._hideTrack(this.parentNode.id);//"this" is the svg element
	});

	$(this.svg).mousedown(function(event) {
		var x = parseInt(trackSvg.features.getAttribute("x")) - event.clientX;
		$(this).mousemove(function(event){
//			console.log(x+event.clientX);
//			if((x + event.clientX)%_this.pixelBase==0){
				trackSvg.features.setAttribute("x",(x + event.clientX));
//			}
		});
	});
	$(this.svg).mouseup(function(event) {
		$(this).off('mousemove');
	});

	trackData.onRetrieve.addEventListener(function(sender,data){
//		console.log(trackData.featureCache)
		trackSvg.addFeatures(data);
	});

	this.height += trackSvg.getHeight();

	trackData = this.trackDataList.trackList[i];
	this.svg.setAttribute("height",this.height);
	this.currentLine.setAttribute("y2",this.height);
};

TrackSvgLayout.prototype._redraw = function(){
	var _this = this;
	var trackSvg = null;
	var lastY = 25;
	for ( var i = 0; i < this.trackSvgList.length; i++) {
		trackSvg = this.trackSvgList[i];
		if(this.swapHash[trackSvg.id].visible){
			trackSvg.main.setAttribute("y",lastY);
			lastY += trackSvg.getHeight();
		}
	}
};

//This routine is called when track order modified
TrackSvgLayout.prototype._reallocateAbove = function(trackMainId){
	var i = this.swapHash[trackMainId].index;
	console.log(i+" quiere moverse 1 posicion arriba");
	if(i>0){
		var aboveTrack=this.trackSvgList[i-1];
		var underTrack=this.trackSvgList[i];

		var y = parseInt(aboveTrack.main.getAttribute("y"));
		var h = parseInt(underTrack.main.getAttribute("height"));
		aboveTrack.main.setAttribute("y",y+h);
		underTrack.main.setAttribute("y",y);

		this.trackSvgList[i] = aboveTrack;
		this.trackSvgList[i-1] = underTrack;
		this.swapHash[aboveTrack.id].index=i;
		this.swapHash[underTrack.id].index=i-1;
	}else{
		console.log("ya esta en la mas alta");
	}
};
//This routine is called when track order modified
TrackSvgLayout.prototype._reallocateUnder = function(trackMainId){
	var i = this.swapHash[trackMainId].index;
	console.log(i+" quiere moverse 1 posicion abajo");
	if(i+1<this.trackDataList.trackList.length){
		var aboveTrack=this.trackSvgList[i];
		var underTrack=this.trackSvgList[i+1];

		var y = parseInt(aboveTrack.main.getAttribute("y"));
		var h = parseInt(underTrack.main.getAttribute("height"));
		aboveTrack.main.setAttribute("y",y+h);
		underTrack.main.setAttribute("y",y);

		this.trackSvgList[i] = underTrack;
		this.trackSvgList[i+1] = aboveTrack;
		this.swapHash[underTrack.id].index=i;
		this.swapHash[aboveTrack.id].index=i+1;

	}else{
		console.log("abajo del todo");
	}
};

TrackSvgLayout.prototype._hideTrack = function(trackMainId){
	this.swapHash[trackMainId].visible=false;
	var i = this.swapHash[trackMainId].index;
	var track = this.trackSvgList[i];
	this.svg.removeChild(track.main);

	this.height -= track.getHeight();
	this.svg.setAttribute("height",this.height);
	this.currentLine.setAttribute("y2",this.height);

	this._redraw();

	var _this= this;
	setTimeout(function() {
		_this._showTrack(trackMainId);
	},2000);

};

TrackSvgLayout.prototype._showTrack = function(trackMainId){
	this.swapHash[trackMainId].visible=true;
	var i = this.swapHash[trackMainId].index;
	var track = this.trackSvgList[i];
	this.svg.appendChild(track.main);

	this.height += track.getHeight();
	this.svg.setAttribute("height",this.height);
	this.currentLine.setAttribute("y2",this.height);

	this._redraw();
};

TrackSvgLayout.prototype._getPixelsbyBase = function(zoom){
	return this.zoomLevels[zoom];
};

TrackSvgLayout.prototype._createPixelsbyBase = function(){
	this.zoomLevels = new Array();
	var pixelsByBase = 10;
	for ( var i = 100; i >= -40; i-=5) {
		this.zoomLevels[i] = pixelsByBase;
		pixelsByBase = pixelsByBase / 2;
	}
};
<commit_msg>limit cellbase call<commit_after>function TrackSvgLayout(parent, trackDataList, args) {
	var _this = this;
	this.args = args;
	this.id = Math.round(Math.random()*10000000);
	this.trackDataList = trackDataList;

	this.trackSvgList =  new Array();
	this.swapHash = new Object();

	//default values
	this.height=25;

	if (args != null){
		if(args.width != null){
			this.width = args.width;
		}
		if(args.height != null){
			this.height = args.height;
		}
		if(args.position != null){
			this.position = args.position;
		}
		if(args.chromosome != null){
			this.chromosome = args.chromosome;
		}
		if(args.zoom != null){
			this.zoom = args.zoom;
		}
	}
	this._createPixelsbyBase();//create pixelByBase array

	this.pixelBase = this._getPixelsbyBase(this.zoom);

	this.svg = SVG.init(parent,{
		"width":this.width,
		"height":this.height
	});

	var mid = this.width/2;
	this.positionText = SVG.addChild(this.svg,"text",{
		"x":mid-30,
		"y":15,
		"fill":"green"
	});
	this.positionText.textContent = this.position;

	this.currentLine = SVG.addChild(this.svg,"line",{
			"x1":mid,
			"y1":this.height,
			"x2":mid,
			"y2":this.height,
			"stroke-width":"1",
			"stroke":"green"
	});

	this.onZoomChange = new Event();
	this.onMove = new Event();

	trackDataList.onAddTrack.addEventListener(function(sender,index){
		_this.draw(index);
	});
};

TrackSvgLayout.prototype.setHeight = function(height){
	this.height=height;
	this.svg.setAttribute("height",height);
};
TrackSvgLayout.prototype.setZoom = function(zoom){
	this.zoom=zoom;
	this.pixelBase = this._getPixelsbyBase(this.zoom);
	this.onZoomChange.notify();
};

TrackSvgLayout.prototype.draw = function(i){
	var _this = this;

	var trackData = this.trackDataList.getTrack(i);
	var trackSvg = new TrackSvg(this.svg,{
		position:this.position,
		zoom:this.zoom,
		pixelBase:this.pixelBase,
		id:trackData.id,
		width:this.width
	});

	//virtual window
	var halfVirtualWidth = _this.width*3/2;
	var halfVirtualBase =  halfVirtualWidth / _this.pixelBase;
	var virtualStart = parseInt(_this.position - halfVirtualBase);
	var vitualEnd = parseInt(_this.position + halfVirtualBase);
	trackData.retrieveData({chromosome:13,start:virtualStart,end:vitualEnd});

	//on zoom change set new virtual window and update track values
	this.onZoomChange.addEventListener(function(sender,data){
		trackSvg.zoom=_this.zoom;
		trackSvg.pixelBase=_this.pixelBase;
		while ( trackSvg.features.childNodes.length >= 1 )
	    {
			trackSvg.features.removeChild( trackSvg.features.firstChild );
	    }
		trackSvg.cache={};
		var halfVirtualBase =  halfVirtualWidth / _this.pixelBase;
		var virtualStart = parseInt(_this.position - halfVirtualBase);
		var vitualEnd = parseInt(_this.position + halfVirtualBase);
		if(virtualStart<0){
			virtualStart=1;
		}
		if(vitualEnd>300000000){
			vitualEnd=300000000;
		}
		trackData.retrieveData({chromosome:13,start:virtualStart,end:vitualEnd});
	});

	this.trackSvgList.push(trackSvg);
	this.swapHash[trackSvg.id] = {index:i,visible:true};
	trackSvg.setY(this.height);
	trackSvg.draw();

	//XXX se puede mover?
	$(trackSvg.upRect).bind("click",function(event){
		_this._reallocateAbove(this.parentNode.id);//"this" is the svg element
	});
	$(trackSvg.downRect).bind("click",function(event){
		_this._reallocateUnder(this.parentNode.id);//"this" is the svg element
	});
	$(trackSvg.hideRect).bind("click",function(event){
		_this._hideTrack(this.parentNode.id);//"this" is the svg element
	});

	$(this.svg).mousedown(function(event) {
		var x = parseInt(trackSvg.features.getAttribute("x")) - event.clientX;
		$(this).mousemove(function(event){
//			console.log(x+event.clientX);
//			if((x + event.clientX)%_this.pixelBase==0){
				trackSvg.features.setAttribute("x",(x + event.clientX));
//			}
		});
	});
	$(this.svg).mouseup(function(event) {
		$(this).off('mousemove');
	});

	trackData.onRetrieve.addEventListener(function(sender,data){
//		console.log(trackData.featureCache)
		trackSvg.addFeatures(data);
	});

	this.height += trackSvg.getHeight();

	trackData = this.trackDataList.trackList[i];
	this.svg.setAttribute("height",this.height);
	this.currentLine.setAttribute("y2",this.height);
};

TrackSvgLayout.prototype._redraw = function(){
	var _this = this;
	var trackSvg = null;
	var lastY = 25;
	for ( var i = 0; i < this.trackSvgList.length; i++) {
		trackSvg = this.trackSvgList[i];
		if(this.swapHash[trackSvg.id].visible){
			trackSvg.main.setAttribute("y",lastY);
			lastY += trackSvg.getHeight();
		}
	}
};

//This routine is called when track order modified
TrackSvgLayout.prototype._reallocateAbove = function(trackMainId){
	var i = this.swapHash[trackMainId].index;
	console.log(i+" quiere moverse 1 posicion arriba");
	if(i>0){
		var aboveTrack=this.trackSvgList[i-1];
		var underTrack=this.trackSvgList[i];

		var y = parseInt(aboveTrack.main.getAttribute("y"));
		var h = parseInt(underTrack.main.getAttribute("height"));
		aboveTrack.main.setAttribute("y",y+h);
		underTrack.main.setAttribute("y",y);

		this.trackSvgList[i] = aboveTrack;
		this.trackSvgList[i-1] = underTrack;
		this.swapHash[aboveTrack.id].index=i;
		this.swapHash[underTrack.id].index=i-1;
	}else{
		console.log("ya esta en la mas alta");
	}
};
//This routine is called when track order modified
TrackSvgLayout.prototype._reallocateUnder = function(trackMainId){
	var i = this.swapHash[trackMainId].index;
	console.log(i+" quiere moverse 1 posicion abajo");
	if(i+1<this.trackDataList.trackList.length){
		var aboveTrack=this.trackSvgList[i];
		var underTrack=this.trackSvgList[i+1];

		var y = parseInt(aboveTrack.main.getAttribute("y"));
		var h = parseInt(underTrack.main.getAttribute("height"));
		aboveTrack.main.setAttribute("y",y+h);
		underTrack.main.setAttribute("y",y);

		this.trackSvgList[i] = underTrack;
		this.trackSvgList[i+1] = aboveTrack;
		this.swapHash[underTrack.id].index=i;
		this.swapHash[aboveTrack.id].index=i+1;

	}else{
		console.log("abajo del todo");
	}
};

TrackSvgLayout.prototype._hideTrack = function(trackMainId){
	this.swapHash[trackMainId].visible=false;
	var i = this.swapHash[trackMainId].index;
	var track = this.trackSvgList[i];
	this.svg.removeChild(track.main);

	this.height -= track.getHeight();
	this.svg.setAttribute("height",this.height);
	this.currentLine.setAttribute("y2",this.height);

	this._redraw();

	var _this= this;
	setTimeout(function() {
		_this._showTrack(trackMainId);
	},2000);

};

TrackSvgLayout.prototype._showTrack = function(trackMainId){
	this.swapHash[trackMainId].visible=true;
	var i = this.swapHash[trackMainId].index;
	var track = this.trackSvgList[i];
	this.svg.appendChild(track.main);

	this.height += track.getHeight();
	this.svg.setAttribute("height",this.height);
	this.currentLine.setAttribute("y2",this.height);

	this._redraw();
};

TrackSvgLayout.prototype._getPixelsbyBase = function(zoom){
	return this.zoomLevels[zoom];
};

TrackSvgLayout.prototype._createPixelsbyBase = function(){
	this.zoomLevels = new Array();
	var pixelsByBase = 10;
	for ( var i = 100; i >= -40; i-=5) {
		this.zoomLevels[i] = pixelsByBase;
		pixelsByBase = pixelsByBase / 2;
	}
};
<|endoftext|>


<commit_before>var nconf = require('nconf'),
    mongo = require('mongodb'),
    path = require('path'),
    fs = require('fs'),
    utils = require('../../lib/utils');

nconf.file({ file: 'gebo.json' });
var TEST_DB = utils.getMongoDbName(nconf.get('testDb'));

//var gebo = require('../../schemata/gebo')(TEST_DB),
//    agentSchema = require('../../schemata/agent');

exports.onLoad = {

    'Load and initialize every file in the actions folder': function(test) {
        test.expect(15);
        // Note: actions, not action, as above
        var actions = require('../../actions')(TEST_DB);
        test.equal(typeof actions.dbExists, 'function');
        test.equal(typeof actions.getCollection, 'function');
        test.equal(typeof actions.save, 'function');
        test.equal(typeof actions.cp, 'function');
        test.equal(typeof actions.rm, 'function');
        test.equal(typeof actions.rmdir, 'function');
        test.equal(typeof actions.ls, 'function');
        test.equal(typeof actions.createDatabase, 'function');
        test.equal(typeof actions.dropDatabase, 'function');
        test.equal(typeof actions.registerAgent, 'function');
        test.equal(typeof actions.deregisterAgent, 'function');
        test.equal(typeof actions.friend, 'function');
        test.equal(typeof actions.defriend, 'function');
        test.equal(typeof actions.grantAccess, 'function');
        test.equal(typeof actions.certificate, 'function');
        test.done();
    },
};

exports.add = {

    tearDown: function(callback) {
        var files = fs.readdirSync(__dirname + '/../../actions');

        files.forEach(function(file) {
            if (require.cache[path.resolve(__dirname + '/../../actions/' + file)]) {
              delete require.cache[path.resolve(__dirname + '/../../actions/' + file)]
            }
        });
        callback();
    },

    'Add a single action function': function(test) {
        test.expect(3);

        var actions = require('../../actions')(TEST_DB);
        test.equal(actions.testAction, undefined);

        // Create a new action
        function testAction() {
                return 'testAction, yeah yeah!';
              };

        actions.add(testAction);

        test.equal(typeof actions.testAction, 'function');
        test.equal(actions.testAction(), 'testAction, yeah yeah!');

        test.done();
    },

    'Add a single action from function assigned to variable': function(test) {
        test.expect(3);

        var actions = require('../../actions')(TEST_DB);
        test.equal(actions.testAction, undefined);

        // Create a new action
        var testAction = function() {
                return 'testAction, yeah yeah!';
              };

        actions.add('testAction', testAction);

        test.equal(typeof actions.testAction, 'function');
        test.equal(actions.testAction(), 'testAction, yeah yeah!');

        test.done();
    },

    'Throw an error if function provided has no name': function(test) {
        test.expect(2);

        var actions = require('../../actions')(TEST_DB);
        test.equal(actions.testAction, undefined);

        // Create a new action
        var testAction = function() {
                return 'testAction, yeah yeah!';
              };

        try {
            actions.add(testAction);
            test.ok(false, 'This should throw an error');
        }
        catch(err) {
            test.equal(err.message, 'This action needs a name');
        }

        test.done();
    },

    'Add a module with actions': function(test) {
        test.expect(6);

        var actions = require('../../actions')(TEST_DB);
        test.equal(actions.testAction1, undefined);
        test.equal(actions.testAction2, undefined);

        var mod = require('./mocks/testActions')('some@email.com');
        actions.add(mod);

        test.equal(typeof actions.testAction1, 'function');
        test.equal(actions.testAction1(), 'testAction1, yeah yeah!');
        test.equal(typeof actions.testAction2, 'function');
        test.equal(actions.testAction2(), 'testAction2, yeah yeah!');

        test.done();
    },
};

exports.remove = {
    'Remove a single action': function(test) {
        test.expect(6);

        var actions = require('../../actions')(TEST_DB);
        test.equal(actions.testAction1, undefined);
        test.equal(actions.testAction2, undefined);

        var mod = require('./mocks/testActions')('some@email.com');
        actions.add(mod);

        test.equal(typeof actions.testAction1, 'function');
        test.equal(typeof actions.testAction2, 'function');

        actions.remove('testAction1');
        test.equal(actions.testAction1, undefined);
        test.equal(typeof actions.testAction2, 'function');

        test.done();
    },
};

<commit_msg>Remove commented code<commit_after>var nconf = require('nconf'),
    mongo = require('mongodb'),
    path = require('path'),
    fs = require('fs'),
    utils = require('../../lib/utils');

nconf.file({ file: 'gebo.json' });
var TEST_DB = utils.getMongoDbName(nconf.get('testDb'));

exports.onLoad = {

    'Load and initialize every file in the actions folder': function(test) {
        test.expect(15);
        // Note: actions, not action, as above
        var actions = require('../../actions')(TEST_DB);
        test.equal(typeof actions.dbExists, 'function');
        test.equal(typeof actions.getCollection, 'function');
        test.equal(typeof actions.save, 'function');
        test.equal(typeof actions.cp, 'function');
        test.equal(typeof actions.rm, 'function');
        test.equal(typeof actions.rmdir, 'function');
        test.equal(typeof actions.ls, 'function');
        test.equal(typeof actions.createDatabase, 'function');
        test.equal(typeof actions.dropDatabase, 'function');
        test.equal(typeof actions.registerAgent, 'function');
        test.equal(typeof actions.deregisterAgent, 'function');
        test.equal(typeof actions.friend, 'function');
        test.equal(typeof actions.defriend, 'function');
        test.equal(typeof actions.grantAccess, 'function');
        test.equal(typeof actions.certificate, 'function');
        test.done();
    },
};

exports.add = {

    tearDown: function(callback) {
        var files = fs.readdirSync(__dirname + '/../../actions');

        files.forEach(function(file) {
            if (require.cache[path.resolve(__dirname + '/../../actions/' + file)]) {
              delete require.cache[path.resolve(__dirname + '/../../actions/' + file)]
            }
        });
        callback();
    },

    'Add a single action function': function(test) {
        test.expect(3);

        var actions = require('../../actions')(TEST_DB);
        test.equal(actions.testAction, undefined);

        // Create a new action
        function testAction() {
                return 'testAction, yeah yeah!';
              };

        actions.add(testAction);

        test.equal(typeof actions.testAction, 'function');
        test.equal(actions.testAction(), 'testAction, yeah yeah!');

        test.done();
    },

    'Add a single action from function assigned to variable': function(test) {
        test.expect(3);

        var actions = require('../../actions')(TEST_DB);
        test.equal(actions.testAction, undefined);

        // Create a new action
        var testAction = function() {
                return 'testAction, yeah yeah!';
              };

        actions.add('testAction', testAction);

        test.equal(typeof actions.testAction, 'function');
        test.equal(actions.testAction(), 'testAction, yeah yeah!');

        test.done();
    },

    'Throw an error if function provided has no name': function(test) {
        test.expect(2);

        var actions = require('../../actions')(TEST_DB);
        test.equal(actions.testAction, undefined);

        // Create a new action
        var testAction = function() {
                return 'testAction, yeah yeah!';
              };

        try {
            actions.add(testAction);
            test.ok(false, 'This should throw an error');
        }
        catch(err) {
            test.equal(err.message, 'This action needs a name');
        }

        test.done();
    },

    'Add a module with actions': function(test) {
        test.expect(6);

        var actions = require('../../actions')(TEST_DB);
        test.equal(actions.testAction1, undefined);
        test.equal(actions.testAction2, undefined);

        var mod = require('./mocks/testActions')('some@email.com');
        actions.add(mod);

        test.equal(typeof actions.testAction1, 'function');
        test.equal(actions.testAction1(), 'testAction1, yeah yeah!');
        test.equal(typeof actions.testAction2, 'function');
        test.equal(actions.testAction2(), 'testAction2, yeah yeah!');

        test.done();
    },
};

exports.remove = {
    'Remove a single action': function(test) {
        test.expect(6);

        var actions = require('../../actions')(TEST_DB);
        test.equal(actions.testAction1, undefined);
        test.equal(actions.testAction2, undefined);

        var mod = require('./mocks/testActions')('some@email.com');
        actions.add(mod);

        test.equal(typeof actions.testAction1, 'function');
        test.equal(typeof actions.testAction2, 'function');

        actions.remove('testAction1');
        test.equal(actions.testAction1, undefined);
        test.equal(typeof actions.testAction2, 'function');

        test.done();
    },
};

<|endoftext|>


<commit_before>"use strict";
const assert = require("assert");
const vm = require("vm");

const assertThrows = require("./assertThrows");
const conversions = require("..");

// Not supported in Node v10, so we'll skip the tests for detached ArrayBuffers there.
let MessageChannel;
try {
  // eslint-disable-next-line global-require
  MessageChannel = require("worker_threads").MessageChannel;
} catch {
  // eslint-disable-next-line no-console
  console.warn("Skipping tests that require the worker_threads module");
}

function commonNotOk(sut) {
  it("should throw a TypeError for `undefined`", () => {
    assertThrows(sut, [undefined], TypeError);
  });

  it("should throw a TypeError for `null`", () => {
    assertThrows(sut, [null], TypeError);
  });

  it("should throw a TypeError for `true`", () => {
    assertThrows(sut, [true], TypeError);
  });

  it("should throw a TypeError for `false`", () => {
    assertThrows(sut, [false], TypeError);
  });

  it("should throw a TypeError for `Infinity`", () => {
    assertThrows(sut, [Infinity], TypeError);
  });

  it("should throw a TypeError for `NaN`", () => {
    assertThrows(sut, [NaN], TypeError);
  });

  it("should throw a TypeError for `0`", () => {
    assertThrows(sut, [0], TypeError);
  });

  it("should throw a TypeError for `''`", () => {
    assertThrows(sut, [""], TypeError);
  });

  it("should throw a TypeError for `Symbol.iterator`", () => {
    assertThrows(sut, [Symbol.iterator], TypeError);
  });

  it("should throw a TypeError for `{}`", () => {
    assertThrows(sut, [{}], TypeError);
  });

  it("should throw a TypeError for `() => {}`", () => {
    assertThrows(sut, [() => {}], TypeError);
  });
}

function testOk(name, sut, create) {
  it(`should return input for ${name}`, () => {
    const obj = create();
    assert.strictEqual(sut(obj), obj);
  });
}

function testNotOk(name, sut, create) {
  it(`should throw a TypeError for ${name}`, () => {
    assertThrows(sut, [create()], TypeError);
  });
}

const differentRealm = vm.createContext();

const bufferSourceConstructors = [
  DataView,
  ArrayBuffer,
  Int8Array,
  Int16Array,
  Int32Array,
  Uint8Array,
  Uint16Array,
  Uint32Array,
  Uint8ClampedArray,
  Float32Array,
  Float64Array
];

const bufferSourceCreators = [
  {
    typeName: "ArrayBuffer",
    isShared: false,
    isDetached: false,
    label: "ArrayBuffer same realm",
    creator: () => new ArrayBuffer(0)
  },
  {
    typeName: "SharedArrayBuffer",
    isShared: true,
    isDetached: false,
    label: "SharedArrayBuffer same realm",
    creator: () => new SharedArrayBuffer(0)
  }
];

if (MessageChannel) {
  bufferSourceCreators.push({
    typeName: "ArrayBuffer",
    isShared: false,
    isDetached: true,
    label: "detached ArrayBuffer",
    creator: () => {
      const value = new ArrayBuffer(0);
      const { port1 } = new MessageChannel();
      port1.postMessage(undefined, [value]);
      return value;
    }
  });
}

for (const constructor of bufferSourceConstructors) {
  if (constructor === ArrayBuffer) {
    continue;
  }

  const { name } = constructor;
  bufferSourceCreators.push(
    {
      typeName: name,
      isShared: false,
      isDetached: false,
      isForged: false,
      label: `${name} same realm`,
      creator: () => new constructor(new ArrayBuffer(0))
    },
    {
      typeName: name,
      isShared: false,
      isDetached: false,
      isForged: false,
      label: `${name} different realm`,
      creator: () => vm.runInContext(`new ${constructor.name}(new ArrayBuffer(0))`, differentRealm)
    },
    {
      typeName: name,
      isShared: true,
      isDetached: false,
      isForged: false,
      label: `${name} SharedArrayBuffer same realm`,
      creator: () => new constructor(new SharedArrayBuffer(0))
    },
    {
      typeName: name,
      isShared: true,
      isDetached: false,
      isForged: false,
      label: `${name} SharedArrayBuffer different realm`,
      creator: () => vm.runInContext(`new ${constructor.name}(new SharedArrayBuffer(0))`, differentRealm)
    },
    {
      typeName: name,
      isShared: false,
      isDetached: false,
      isForged: true,
      label: `forged ${name}`,
      creator: () => Object.create(constructor.prototype, { [Symbol.toStringTag]: { value: name } })
    }
  );

  if (MessageChannel) {
    bufferSourceCreators.push({
      typeName: name,
      isShared: false,
      isDetached: true,
      isForged: false,
      label: `detached ${name}`,
      creator: () => {
        const value = new constructor(new ArrayBuffer(0));
        const { port1 } = new MessageChannel();
        port1.postMessage(undefined, [value.buffer]);
        return value;
      }
    });
  }
}

for (const type of bufferSourceConstructors) {
  const typeName = type.name;
  const sut = conversions[typeName];

  describe(`WebIDL ${typeName} type`, () => {
    for (const innerType of bufferSourceCreators) {
      const testFunction =
        innerType.typeName === typeName &&
        !innerType.isShared &&
        !innerType.isDetached &&
        !innerType.isForged ?
          testOk :
          testNotOk;

      testFunction(innerType.label, sut, innerType.creator);
    }

    commonNotOk(sut);

    describe("with [AllowShared]", () => {
      const allowSharedSUT = (v, opts) => conversions[typeName](v, { ...opts, allowShared: true });

      for (const { label, creator, typeName: innerTypeName, isDetached, isForged } of bufferSourceCreators) {
        const testFunction = innerTypeName === typeName && !isDetached && !isForged ? testOk : testNotOk;
        testFunction(label, allowSharedSUT, creator);
      }

      commonNotOk(allowSharedSUT);
    });
  });
}

describe("WebIDL ArrayBufferView type", () => {
  const sut = conversions.ArrayBufferView;

  for (const { label, typeName, isShared, isDetached, isForged, creator } of bufferSourceCreators) {
    const testFunction =
      typeName !== "ArrayBuffer" &&
      typeName !== "SharedArrayBuffer" &&
      !isShared &&
      !isDetached &&
      !isForged ?
        testOk :
        testNotOk;

    testFunction(label, sut, creator);
  }

  commonNotOk(sut);

  describe("with [AllowShared]", () => {
    const allowSharedSUT = (v, opts) => conversions.ArrayBufferView(v, { ...opts, allowShared: true });

    for (const { label, creator, typeName, isDetached, isForged } of bufferSourceCreators) {
      const testFunction =
        typeName !== "ArrayBuffer" &&
        typeName !== "SharedArrayBuffer" &&
        !isDetached &&
        !isForged ?
          testOk :
          testNotOk;

      testFunction(label, allowSharedSUT, creator);
    }

    commonNotOk(allowSharedSUT);
  });
});

describe("WebIDL BufferSource type", () => {
  const sut = conversions.BufferSource;

  for (const { label, creator, isShared, isDetached, isForged } of bufferSourceCreators) {
    const testFunction = !isShared && !isDetached && !isForged ? testOk : testNotOk;
    testFunction(label, sut, creator);
  }

  commonNotOk(sut);

  describe("with [AllowShared]", () => {
    const allowSharedSUT = (v, opts) => conversions.BufferSource(v, { ...opts, allowShared: true });

    for (const { label, creator, isDetached, isForged } of bufferSourceCreators) {
      const testFunction = !isDetached && !isForged ? testOk : testNotOk;
      testFunction(label, allowSharedSUT, creator);
    }

    commonNotOk(allowSharedSUT);
  });
});
<commit_msg>Remove Node.js v10 workaround in the tests<commit_after>"use strict";
const assert = require("assert");
const vm = require("vm");
const { MessageChannel } = require("worker_threads");

const assertThrows = require("./assertThrows");
const conversions = require("..");

function commonNotOk(sut) {
  it("should throw a TypeError for `undefined`", () => {
    assertThrows(sut, [undefined], TypeError);
  });

  it("should throw a TypeError for `null`", () => {
    assertThrows(sut, [null], TypeError);
  });

  it("should throw a TypeError for `true`", () => {
    assertThrows(sut, [true], TypeError);
  });

  it("should throw a TypeError for `false`", () => {
    assertThrows(sut, [false], TypeError);
  });

  it("should throw a TypeError for `Infinity`", () => {
    assertThrows(sut, [Infinity], TypeError);
  });

  it("should throw a TypeError for `NaN`", () => {
    assertThrows(sut, [NaN], TypeError);
  });

  it("should throw a TypeError for `0`", () => {
    assertThrows(sut, [0], TypeError);
  });

  it("should throw a TypeError for `''`", () => {
    assertThrows(sut, [""], TypeError);
  });

  it("should throw a TypeError for `Symbol.iterator`", () => {
    assertThrows(sut, [Symbol.iterator], TypeError);
  });

  it("should throw a TypeError for `{}`", () => {
    assertThrows(sut, [{}], TypeError);
  });

  it("should throw a TypeError for `() => {}`", () => {
    assertThrows(sut, [() => {}], TypeError);
  });
}

function testOk(name, sut, create) {
  it(`should return input for ${name}`, () => {
    const obj = create();
    assert.strictEqual(sut(obj), obj);
  });
}

function testNotOk(name, sut, create) {
  it(`should throw a TypeError for ${name}`, () => {
    assertThrows(sut, [create()], TypeError);
  });
}

const differentRealm = vm.createContext();

const bufferSourceConstructors = [
  DataView,
  ArrayBuffer,
  Int8Array,
  Int16Array,
  Int32Array,
  Uint8Array,
  Uint16Array,
  Uint32Array,
  Uint8ClampedArray,
  Float32Array,
  Float64Array
];

const bufferSourceCreators = [
  {
    typeName: "ArrayBuffer",
    isShared: false,
    isDetached: false,
    label: "ArrayBuffer same realm",
    creator: () => new ArrayBuffer(0)
  },
  {
    typeName: "SharedArrayBuffer",
    isShared: true,
    isDetached: false,
    label: "SharedArrayBuffer same realm",
    creator: () => new SharedArrayBuffer(0)
  },
  {
    typeName: "ArrayBuffer",
    isShared: false,
    isDetached: true,
    label: "detached ArrayBuffer",
    creator: () => {
      const value = new ArrayBuffer(0);
      const { port1 } = new MessageChannel();
      port1.postMessage(undefined, [value]);
      return value;
    }
  }
];

for (const constructor of bufferSourceConstructors) {
  if (constructor === ArrayBuffer) {
    continue;
  }

  const { name } = constructor;
  bufferSourceCreators.push(
    {
      typeName: name,
      isShared: false,
      isDetached: false,
      isForged: false,
      label: `${name} same realm`,
      creator: () => new constructor(new ArrayBuffer(0))
    },
    {
      typeName: name,
      isShared: false,
      isDetached: false,
      isForged: false,
      label: `${name} different realm`,
      creator: () => vm.runInContext(`new ${constructor.name}(new ArrayBuffer(0))`, differentRealm)
    },
    {
      typeName: name,
      isShared: true,
      isDetached: false,
      isForged: false,
      label: `${name} SharedArrayBuffer same realm`,
      creator: () => new constructor(new SharedArrayBuffer(0))
    },
    {
      typeName: name,
      isShared: true,
      isDetached: false,
      isForged: false,
      label: `${name} SharedArrayBuffer different realm`,
      creator: () => vm.runInContext(`new ${constructor.name}(new SharedArrayBuffer(0))`, differentRealm)
    },
    {
      typeName: name,
      isShared: false,
      isDetached: false,
      isForged: true,
      label: `forged ${name}`,
      creator: () => Object.create(constructor.prototype, { [Symbol.toStringTag]: { value: name } })
    }
  );

  if (MessageChannel) {
    bufferSourceCreators.push({
      typeName: name,
      isShared: false,
      isDetached: true,
      isForged: false,
      label: `detached ${name}`,
      creator: () => {
        const value = new constructor(new ArrayBuffer(0));
        const { port1 } = new MessageChannel();
        port1.postMessage(undefined, [value.buffer]);
        return value;
      }
    });
  }
}

for (const type of bufferSourceConstructors) {
  const typeName = type.name;
  const sut = conversions[typeName];

  describe(`WebIDL ${typeName} type`, () => {
    for (const innerType of bufferSourceCreators) {
      const testFunction =
        innerType.typeName === typeName &&
        !innerType.isShared &&
        !innerType.isDetached &&
        !innerType.isForged ?
          testOk :
          testNotOk;

      testFunction(innerType.label, sut, innerType.creator);
    }

    commonNotOk(sut);

    describe("with [AllowShared]", () => {
      const allowSharedSUT = (v, opts) => conversions[typeName](v, { ...opts, allowShared: true });

      for (const { label, creator, typeName: innerTypeName, isDetached, isForged } of bufferSourceCreators) {
        const testFunction = innerTypeName === typeName && !isDetached && !isForged ? testOk : testNotOk;
        testFunction(label, allowSharedSUT, creator);
      }

      commonNotOk(allowSharedSUT);
    });
  });
}

describe("WebIDL ArrayBufferView type", () => {
  const sut = conversions.ArrayBufferView;

  for (const { label, typeName, isShared, isDetached, isForged, creator } of bufferSourceCreators) {
    const testFunction =
      typeName !== "ArrayBuffer" &&
      typeName !== "SharedArrayBuffer" &&
      !isShared &&
      !isDetached &&
      !isForged ?
        testOk :
        testNotOk;

    testFunction(label, sut, creator);
  }

  commonNotOk(sut);

  describe("with [AllowShared]", () => {
    const allowSharedSUT = (v, opts) => conversions.ArrayBufferView(v, { ...opts, allowShared: true });

    for (const { label, creator, typeName, isDetached, isForged } of bufferSourceCreators) {
      const testFunction =
        typeName !== "ArrayBuffer" &&
        typeName !== "SharedArrayBuffer" &&
        !isDetached &&
        !isForged ?
          testOk :
          testNotOk;

      testFunction(label, allowSharedSUT, creator);
    }

    commonNotOk(allowSharedSUT);
  });
});

describe("WebIDL BufferSource type", () => {
  const sut = conversions.BufferSource;

  for (const { label, creator, isShared, isDetached, isForged } of bufferSourceCreators) {
    const testFunction = !isShared && !isDetached && !isForged ? testOk : testNotOk;
    testFunction(label, sut, creator);
  }

  commonNotOk(sut);

  describe("with [AllowShared]", () => {
    const allowSharedSUT = (v, opts) => conversions.BufferSource(v, { ...opts, allowShared: true });

    for (const { label, creator, isDetached, isForged } of bufferSourceCreators) {
      const testFunction = !isDetached && !isForged ? testOk : testNotOk;
      testFunction(label, allowSharedSUT, creator);
    }

    commonNotOk(allowSharedSUT);
  });
});
<|endoftext|>


<commit_before>const test = require('tape')
const render = require('../../lib/render')
const parse = require('parse-element')
const strip = require('strip-formatting')
const s = require('brisky-struct')

require('brisky-core').prototype.inject(require('../'))

test('context - static class name', t => {
  const state = s({})

  const types = {
    steps: {
      class: true,
      one: { text: 1 },
      two: { text: 2 },
      three: { text: 3 }
    }
  }

  const page1 = {
    steps: {
      type: 'steps',
      one: { class: 'active' }
    }
  }

  const page2 = {
    $: 'page2',
    steps: {
      type: 'steps',
      two: { class: 'active' }
    }
  }

  const app = render({ types, page1, page2 }, state)

  state.set({ page2: true })

  t.same(
    parse(app),
    strip(`

1

2

3

1

2

3

    `),
    'correct inheritance'
  )
  t.end()
})

test('context - keys as class name', t => {
  const elem = render({
    types: {
      elem: {
        class: {
          val: true,
          thing: {
            $: 'simpleClass'
          }
        }
      }
    },
    elem1: { type: 'elem' },
    elem2: { type: 'elem' }
  }, {
    simpleClass: 'simple-class'
  })
  t.equals(elem.childNodes[0].className, 'elem1 simple-class', 'context 1 correct key')
  t.equals(elem.childNodes[1].className, 'elem2 simple-class', 'context 2 correct key')
  t.end()
})

test('context - class subscription with nested properties', t => {
  var node
  const state = s({
    thing: {
      active: true
    }
  })

  const elem = {
    types: {
      thing: {
        class: {
          default: 'hello'
        }
      }
    },
    thing: {
      $: 'thing',
      type: 'thing',
      class: {
        active: {
          $: 'active',
          $transform: (val) => val && 'active'
        }
      }
    }
  }

  node = render(elem, state)
  t.equals(node.childNodes[0].className, 'hello active', 'init with subs')

  state.thing.active = false
  node = render(elem, state)
  t.equals(node.childNodes[0].className, 'hello', 'removed class')

  t.end()
})

test('context - remove field on inherited class', t => {
  const state = s({})

  const elem = render({
    types: {
      elem: {
        class: {
          hello: true,
          thing: {
            $: 'simpleClass'
          }
        }
      }
    },
    elem1: { type: 'elem' },
    elem2: { type: 'elem', class: { bla: { $: 'bla' } } }
  }, state)

  t.equals(elem.childNodes[0].className, 'hello', '1 initial')
  t.equals(elem.childNodes[1].className, 'hello', '2 initial')

  state.set({ simpleClass: true })
  t.equals(elem.childNodes[0].className, 'hello thing', '1 after state "true"')
  t.equals(elem.childNodes[1].className, 'hello thing', '2 after state "true"')

  state.set({ bla: true })
  t.equals(elem.childNodes[1].className, 'hello thing bla', '2 after state "true"')

  state.simpleClass.set(null)
  t.equals(elem.childNodes[0].className, 'hello', '1 after removal of $root.simpleClass')
  t.equals(elem.childNodes[1].className, 'hello bla', '2 after removal of $root.simpleClass')

  state.bla.set(null)
  t.equals(elem.childNodes[1].className, 'hello', '2 after removal of $root.bal')
  t.end()
})
<commit_msg>remove core deps<commit_after>const test = require('tape')
const render = require('../../lib/render')
const parse = require('parse-element')
const strip = require('strip-formatting')
const s = require('brisky-struct')

test('context - static class name', t => {
  const state = s({})

  const types = {
    steps: {
      class: true,
      one: { text: 1 },
      two: { text: 2 },
      three: { text: 3 }
    }
  }

  const page1 = {
    steps: {
      type: 'steps',
      one: { class: 'active' }
    }
  }

  const page2 = {
    $: 'page2',
    steps: {
      type: 'steps',
      two: { class: 'active' }
    }
  }

  const app = render({ types, page1, page2 }, state)

  state.set({ page2: true })

  t.same(
    parse(app),
    strip(`

1

2

3

1

2

3

    `),
    'correct inheritance'
  )
  t.end()
})

test('context - keys as class name', t => {
  const elem = render({
    types: {
      elem: {
        class: {
          val: true,
          thing: {
            $: 'simpleClass'
          }
        }
      }
    },
    elem1: { type: 'elem' },
    elem2: { type: 'elem' }
  }, {
    simpleClass: 'simple-class'
  })
  t.equals(elem.childNodes[0].className, 'elem1 simple-class', 'context 1 correct key')
  t.equals(elem.childNodes[1].className, 'elem2 simple-class', 'context 2 correct key')
  t.end()
})

test('context - class subscription with nested properties', t => {
  var node
  const state = s({
    thing: {
      active: true
    }
  })

  const elem = {
    types: {
      thing: {
        class: {
          default: 'hello'
        }
      }
    },
    thing: {
      $: 'thing',
      type: 'thing',
      class: {
        active: {
          $: 'active',
          $transform: (val) => val && 'active'
        }
      }
    }
  }

  node = render(elem, state)
  t.equals(node.childNodes[0].className, 'hello active', 'init with subs')

  state.thing.active = false
  node = render(elem, state)
  t.equals(node.childNodes[0].className, 'hello', 'removed class')

  t.end()
})

test('context - remove field on inherited class', t => {
  const state = s({})

  const elem = render({
    types: {
      elem: {
        class: {
          hello: true,
          thing: {
            $: 'simpleClass'
          }
        }
      }
    },
    elem1: { type: 'elem' },
    elem2: { type: 'elem', class: { bla: { $: 'bla' } } }
  }, state)

  t.equals(elem.childNodes[0].className, 'hello', '1 initial')
  t.equals(elem.childNodes[1].className, 'hello', '2 initial')

  state.set({ simpleClass: true })
  t.equals(elem.childNodes[0].className, 'hello thing', '1 after state "true"')
  t.equals(elem.childNodes[1].className, 'hello thing', '2 after state "true"')

  state.set({ bla: true })
  t.equals(elem.childNodes[1].className, 'hello thing bla', '2 after state "true"')

  state.simpleClass.set(null)
  t.equals(elem.childNodes[0].className, 'hello', '1 after removal of $root.simpleClass')
  t.equals(elem.childNodes[1].className, 'hello bla', '2 after removal of $root.simpleClass')

  state.bla.set(null)
  t.equals(elem.childNodes[1].className, 'hello', '2 after removal of $root.bal')
  t.end()
})
<|endoftext|>


<commit_before>const {clipboard} = require('electron')

var str;

function processFlow() {

var obtained_text = "How cover details obtained - ";
var obtained = document.getElementById("how-obtained");

var underwriter_text = "Underwriter - ";
var underwriter = document.getElementById("carrier");

var scheme_text = "Scheme - ";
var scheme = document.getElementById("scheme");

var bui_sumsinsured_text = "Buildings SI - ";
var bui_sumsinsured = document.getElementById("bui-si");

var con_sumsinsured_text = "Contents SI - ";
var con_sumsinsured = document.getElementById("con-si");

var bui_adcover_text = "Buildings AD - ";

if (document.getElementById("bui-ad-q").checked == true) {
	var bui_adcover = "Yes";
} else {
	var bui_adcover = "No";
};

var con_adcover_text = "Buildings AD - ";

if (document.getElementById("con-ad-q").checked == true) {
	var con_adcover = "Yes";
} else {
	var con_adcover = "No";
};

var personal_text = "Personal Belongings/Personal Possessions cover - ";
var personal = document.getElementById("pp-si");

var specified_text = "Specified cover & items - ";
var specified = document.getElementById("spec-si-items").value.replace(/\n\r?/g, "\r\n");

var unspecified_text = "Unspecified cover - ";
var unspecified = document.getElementById("unspec-si");

var standardxs_text = "Standard excesses incl. EOW, etc. - ";
var standardxs = document.getElementById("standard-xs");

var voluntaryxs_text = "Voluntary excesses - ";
var voluntaryxs = document.getElementById("voluntary-xs");

var renewal_text = "Inception/Renewal date - ";
var renewal = document.getElementById("inc-renewal");

var history_text = "Previous claims - ";
var history = document.getElementById("prev-claims").value.replace(/\n\r?/g, "\r\n");

var endorsements_text = "Endorsements - ";
var endorsements = document.getElementById("endorsements").value.replace(/\n\r?/g, "\r\n");

var jph_text = "Any joint policy holders (JPH) - ";
var jph = document.getElementById("jph").value.replace(/\n\r?/g, "\r\n");

if (underwriter.value == "Please select") {

	alert("Please select underwriter first!");

} else {

str = obtained_text + obtained.value + "\r\n\r\n" +
underwriter_text + underwriter.value + "\r\n" +
scheme_text + scheme.value + "\r\n\r\n" +
renewal_text + renewal.value + "\r\n" +
jph_text + jph + "\r\n\r\n" +
bui_sumsinsured_text + bui_sumsinsured.value + "\r\n" +
bui_adcover_text + bui_adcover + "\r\n" +
con_sumsinsured_text + con_sumsinsured.value + "\r\n" +
con_adcover_text + con_adcover + "\r\n" +
personal_text + personal.value + "\r\n" +
unspecified_text + unspecified.value + "\r\n" +
specified_text + specified + "\r\n\r\n" +
standardxs_text + standardxs.value + "\r\n" +
voluntaryxs_text + voluntaryxs.value + "\r\n\r\n" +
history_text + history + "\r\n" +
endorsements_text + endorsements;

// alert(str);

clipboard.writeText(str);

document.getElementById("copy-button").innerText = "Copied!";
document.getElementById("copy-button").className = "copy-button-slow";
	setTimeout(function(){
		document.getElementById("copy-button").style.color = "#3b5166"
		setTimeout(function(){
			document.getElementById("copy-button").className = "copy-button-fast"
			document.getElementById("copy-button").innerText = "Copy to Clipboard";
			document.getElementById("copy-button").style.color = "#FFFFFF";
		}, 700);
	}, 500);
};

};

<commit_msg>Update functions.js<commit_after>const {clipboard} = require('electron')

var str;

function processFlow() {

var obtained_text = "How cover details obtained - ";
var obtained = document.getElementById("how-obtained");

var underwriter_text = "Underwriter - ";
var underwriter = document.getElementById("carrier");

var scheme_text = "Scheme - ";
var scheme = document.getElementById("scheme");

var bui_sumsinsured_text = "Buildings SI - ";
var bui_sumsinsured = document.getElementById("bui-si");

var con_sumsinsured_text = "Contents SI - ";
var con_sumsinsured = document.getElementById("con-si");

var bui_adcover_text = "Buildings AD - ";

var bui_adcover = (document.getElementById("bui-ad-q").checked == true) ? "Yes" : "No";

var con_adcover_text = "Buildings AD - ";

var con_adcover = (document.getElementById("con-ad-q").checked == true) ? "Yes" : "No";

var personal_text = "Personal Belongings/Personal Possessions cover - ";
var personal = document.getElementById("pp-si");

var specified_text = "Specified cover & items - ";
var specified = document.getElementById("spec-si-items").value.replace(/\n\r?/g, "\r\n");

var unspecified_text = "Unspecified cover - ";
var unspecified = document.getElementById("unspec-si");

var standardxs_text = "Standard excesses incl. EOW, etc. - ";
var standardxs = document.getElementById("standard-xs");

var voluntaryxs_text = "Voluntary excesses - ";
var voluntaryxs = document.getElementById("voluntary-xs");

var renewal_text = "Inception/Renewal date - ";
var renewal = document.getElementById("inc-renewal");

var history_text = "Previous claims - ";
var history = document.getElementById("prev-claims").value.replace(/\n\r?/g, "\r\n");

var endorsements_text = "Endorsements - ";
var endorsements = document.getElementById("endorsements").value.replace(/\n\r?/g, "\r\n");

var jph_text = "Any joint policy holders (JPH) - ";
var jph = document.getElementById("jph").value.replace(/\n\r?/g, "\r\n");

if (underwriter.value == "Please select") {

	alert("Please select underwriter first!");

} else {

str = obtained_text + obtained.value + "\r\n\r\n" +
underwriter_text + underwriter.value + "\r\n" +
scheme_text + scheme.value + "\r\n\r\n" +
renewal_text + renewal.value + "\r\n" +
jph_text + jph + "\r\n\r\n" +
bui_sumsinsured_text + bui_sumsinsured.value + "\r\n" +
bui_adcover_text + bui_adcover + "\r\n" +
con_sumsinsured_text + con_sumsinsured.value + "\r\n" +
con_adcover_text + con_adcover + "\r\n" +
personal_text + personal.value + "\r\n" +
unspecified_text + unspecified.value + "\r\n" +
specified_text + specified + "\r\n\r\n" +
standardxs_text + standardxs.value + "\r\n" +
voluntaryxs_text + voluntaryxs.value + "\r\n\r\n" +
history_text + history + "\r\n" +
endorsements_text + endorsements;

// alert(str);

clipboard.writeText(str);

document.getElementById("copy-button").innerText = "Copied!";
document.getElementById("copy-button").className = "copy-button-slow";
	setTimeout(function(){
		document.getElementById("copy-button").style.color = "#3b5166"
		setTimeout(function(){
			document.getElementById("copy-button").className = "copy-button-fast"
			document.getElementById("copy-button").innerText = "Copy to Clipboard";
			document.getElementById("copy-button").style.color = "#FFFFFF";
		}, 700);
	}, 500);
};

};

<|endoftext|>


<commit_before>laundryTimeApp.controller('modalCtrl', function($scope, modalFactory) {

	$scope.modalFactory = modalFactory;

	/* I think this variable doesn't need to be shared
	between controllers */
	$scope.userToBeDeleted = {
		email: "",
		pin: ""
	};

	/* handle functions */
	var handleSuccess = function(data){
		console.log("Success: ");
		console.log(data);
	}

	var handleError = function(res){
		modalFactory.setErrorText("Error: " + res.data.message);
	}

	/* functions */
	$scope.reportModSelChanged = function () {
		modalFactory.reportSelector.show =
		(modalFactory.reportSelector.selected == 5);
	}

	$scope.saveUserCookies = function(){
		modalFactory.saveUserCookies();
	}

	/* html calls */

	/* POST REQUEST */
	$scope.addUserToQueue = function(){
		$scope.getQueue().then( function(){
			modalFactory.addUserToQueue().
			then(function(res){
				/* care with this */
				$scope.getQueue();
				$('#LoginModal').modal('hide');
				$('#LineModal').modal('show');
				modalFactory.setErrorText("");
			},handleError);
		}
		,handleError);
	}

	$scope.reportProblem = function(){
		if(validateDescriptionandUpdate()){
			modalFactory.reportProblem().then(function(res){
				$('#reportModal').modal('hide');
				modalFactory.setErrorText("");
				window.alert("Problem reported successfully.");
			}, handleError);
		}
	}

	/* GET REQUEST */
	$scope.getQueue = function(){
		return modalFactory.getQueue().then(
			function(obj){
				var queue = [];
				for(var i = 0; i < obj.data.queue.length; i++){
					queue.push(obj.data.queue[i]);
				}
				modalFactory.setMachineQueue(queue);
			}
				,handleError);
	}

	/* Validation process for the Login modal */
	$scope.validateLogin = function(){
		if(validatePINandUpdate('LoginPinForm', modalFactory.userInfo.pin)
			& validateEmailandUpdate('LoginEmailForm',modalFactory.userInfo.email))
		{
			/* Everything OK */
			$scope.addUserToQueue();
		}
	}

	/* This method will add 'has-error' to elementId class
	if the PIN is not accepted, true = ok  */
	var validatePINandUpdate = function(elementId, pin){
		if(!checkPIN(pin)){
			document.getElementById(elementId).className = 'form-group has-error';
			return false;
		}else{
			document.getElementById(elementId).className = 'form-group'
			return true;
		}
	}

	/* return true if ok, otherwise false */
	var checkPIN = function(pin){
		return !(pin === undefined
		|| pin.length < 4
		|| isNaN(pin));
	}

	/* This method will add 'has-error' to elementId class
	if the email is not accepted, true = ok  */
	var validateEmailandUpdate = function(elementId, email){
    	if(!checkEmail(email)){
			document.getElementById(elementId).className = 'form-group has-error';
    		return false;
    	}else{
			document.getElementById(elementId).className = 'form-group'
    		return true;
    	}
	}

	/* return true if ok, otherwise false */
	var checkEmail = function(email){
		var re = /\S+@\S+\.\S+/;
		return re.test(email);
	}

	/* true = ok */
	var validateDescriptionandUpdate = function(){
		if(modalFactory.reportSelector.selected === '5'
			&& modalFactory.reportSelector.description.length === 0){
			/* Error */
			document.getElementById('reportFormDescription').className = "form-group has-error";
			return false;
		}else{
			/*everything ok */
			document.getElementById('reportFormDescription').className = "form-group";
			return true;
		}
	}

	/* Calls the factory to remove a user from the queue */
	$scope.deleteUser = function(){
		/* validate pin */
		if(validatePINandUpdate('deletePinForm', $scope.userToBeDeleted.pin)){
			modalFactory.deleteUser($scope.userToBeDeleted.email,
				$scope.userToBeDeleted.pin).then(
				function(res){
					/* everything ok */
					$('#DeleteModal').modal('hide');
					$scope.userToBeDeleted.pin = "";
					modalFactory.setErrorText("");
					window.alert("User deleted successfully.");
				},handleError);
		}
	}

	$scope.dequeueUser = function(){
		/* validate pin */
		if(validatePINandUpdate('deletePinForm', $scope.userToBeDeleted.pin)){
			modalFactory.dequeueUser($scope.userToBeDeleted.email,
				$scope.userToBeDeleted.pin).then(
				function(res){
					/* everything ok */
					$('#DequeueModal').modal('hide');
					$scope.userToBeDeleted.pin = "";
					modalFactory.setErrorText("");
					window.alert("User dequeued successfully.");
				},handleError);
		}
	}

	/* Transition LineModal -> DeleteModal */
	$scope.showDeleteUser = function(user){
		$scope.userToBeDeleted.email = user;
		$('#LineModal').modal('hide');
		$('#deleteUserEmail').text(user);
		$('#DeleteModal').modal('show');
	}

	$scope.showDequeueUser = function(user){
		$scope.userToBeDeleted.email = user;
		$('#LineModal').modal('hide');
		$('#deleteUserEmail').text(user);
		$('#DequeueModal').modal('show');
	}

	$scope.close = function(){
		modalFactory.setErrorText("");
	}

});/* endController */
<commit_msg>Report Problem: Fixed description<commit_after>laundryTimeApp.controller('modalCtrl', function($scope, modalFactory) {

	$scope.modalFactory = modalFactory;

	/* I think this variable doesn't need to be shared
	between controllers */
	$scope.userToBeDeleted = {
		email: "",
		pin: ""
	};

	/* handle functions */
	var handleSuccess = function(data){
		console.log("Success: ");
		console.log(data);
	}

	var handleError = function(res){
		modalFactory.setErrorText("Error: " + res.data.message);
	}

	/* functions */
	$scope.reportModSelChanged = function () {
		modalFactory.reportSelector.show =
		(modalFactory.reportSelector.selected == 5);
	}

	$scope.saveUserCookies = function(){
		modalFactory.saveUserCookies();
	}

	/* html calls */

	/* POST REQUEST */
	$scope.addUserToQueue = function(){
		$scope.getQueue().then( function(){
			modalFactory.addUserToQueue().
			then(function(res){
				/* care with this */
				$scope.getQueue();
				$('#LoginModal').modal('hide');
				$('#LineModal').modal('show');
				modalFactory.setErrorText("");
			},handleError);
		}
		,handleError);
	}

	$scope.reportProblem = function(){
		if(validateDescriptionandUpdate()){
			modalFactory.reportProblem().then(function(res){
				$('#reportModal').modal('hide');
				modalFactory.setErrorText("");
				window.alert("Problem reported successfully.");
			}, handleError);
		}
	}

	/* GET REQUEST */
	$scope.getQueue = function(){
		return modalFactory.getQueue().then(
			function(obj){
				var queue = [];
				for(var i = 0; i < obj.data.queue.length; i++){
					queue.push(obj.data.queue[i]);
				}
				modalFactory.setMachineQueue(queue);
			}
				,handleError);
	}

	/* Validation process for the Login modal */
	$scope.validateLogin = function(){
		if(validatePINandUpdate('LoginPinForm', modalFactory.userInfo.pin)
			& validateEmailandUpdate('LoginEmailForm',modalFactory.userInfo.email))
		{
			/* Everything OK */
			$scope.addUserToQueue();
		}
	}

	/* This method will add 'has-error' to elementId class
	if the PIN is not accepted, true = ok  */
	var validatePINandUpdate = function(elementId, pin){
		if(!checkPIN(pin)){
			document.getElementById(elementId).className += 'has-error';
			return false;
		}else{
			return true;
		}
	}

	/* return true if ok, otherwise false */
	var checkPIN = function(pin){
		return !(pin === undefined
		|| pin.length < 4
		|| isNaN(pin));
	}

	/* This method will add 'has-error' to elementId class
	if the email is not accepted, true = ok  */
	var validateEmailandUpdate = function(elementId, email){
    	if(!checkEmail(email)){
			document.getElementById(elementId).className = 'form-group has-error';
    		return false;
    	}else{
			document.getElementById(elementId).className = 'form-group'
    		return true;
    	}
	}

	/* return true if ok, otherwise false */
	var checkEmail = function(email){
		var re = /\S+@\S+\.\S+/;
		return re.test(email);
	}

	/* true = ok */
	var validateDescriptionandUpdate = function(){
		if(modalFactory.reportSelector.selected === '5'
			&& modalFactory.reportSelector.description.length === 0){
			/* Error */
			document.getElementById('reportFormDescription').className = "form-group has-error";
			return false;
		}else{
			/*everything ok */
			document.getElementById('reportFormDescription').className = "form-group";
			return true;
		}
	}

	/* Calls the factory to remove a user from the queue */
	$scope.deleteUser = function(){
		/* validate pin */
		if(validatePINandUpdate('deletePinForm', $scope.userToBeDeleted.pin)){
			modalFactory.deleteUser($scope.userToBeDeleted.email,
				$scope.userToBeDeleted.pin).then(
				function(res){
					/* everything ok */
					$('#DeleteModal').modal('hide');
					$scope.userToBeDeleted.pin = "";
					modalFactory.setErrorText("");
					window.alert("User deleted successfully.");
				},handleError);
		}
	}

	$scope.dequeueUser = function(){
		/* validate pin */
		if(validatePINandUpdate('deletePinForm', $scope.userToBeDeleted.pin)){
			modalFactory.dequeueUser($scope.userToBeDeleted.email,
				$scope.userToBeDeleted.pin).then(
				function(res){
					/* everything ok */
					$('#DequeueModal').modal('hide');
					$scope.userToBeDeleted.pin = "";
					modalFactory.setErrorText("");
					window.alert("User dequeued successfully.");
				},handleError);
		}
	}

	/* Transition LineModal -> DeleteModal */
	$scope.showDeleteUser = function(user){
		$scope.userToBeDeleted.email = user;
		$('#LineModal').modal('hide');
		$('#deleteUserEmail').text(user);
		$('#DeleteModal').modal('show');
	}

	$scope.showDequeueUser = function(user){
		$scope.userToBeDeleted.email = user;
		$('#LineModal').modal('hide');
		$('#deleteUserEmail').text(user);
		$('#DequeueModal').modal('show');
	}

	$scope.close = function(){
		modalFactory.setErrorText("");
	}

});/* endController */
<|endoftext|>


<commit_before>/*global $:false */
'use strict';

var MovieApp = MovieApp || {
    url: 'http:localhost:3000'
};

$(document).ready(function(){
  console.log('movie_new loaded');
});
<commit_msg>prelim work creating post aajax request to make new movie<commit_after>/*global $:false */
'use strict';

var MovieApp = MovieApp || {
    url: 'http:localhost:3000'
};

MovieApp.createMovie = function(event){
  if (event.preventDefault) event.preventDefault();
  $.ajax({
    url: MovieApp.url + '/movies',
    type: 'POST',
    data: {
      movie: {
        title: $('input#movieTitle').val(),
        gross: $('input#movieGross').val(),
        release: $('input#movieRelease').val(),
        rating: $('input#movierating').val(),
        description: $('textarea#movieDescription').val()
      }
    }
  }).done(function(data){
    MovieApp.resetMovieForm();
    MovieApp.goToMovie(data);
  }).fail();
};

MovieApp.resetMovieForm = function(){
  $('input#movieTitle').val('');
  $('input#movieGross').val('');
  $('input#movieRelease').val('');
  $('input#movieRating').val('');
  $('textArea#movieDescription').val('');
};

MovieApp.goToMovie = function(data){
  console.log(data);
};

$(document).ready(function(){
  // window.location.href = 'http://www.google.com';
  console.log('movie_new loaded');
  $('#movieForm').submit(MovieApp.createMovie);
});
<|endoftext|>


<commit_before>// Parse a color by letting CSS parse it
export function parseColor(color) {
  // Make a div, assign a color, and see what CSS parses it as. The div must temporarily be added to
  // the DOM sothat getComputedStyle works.
  const elem = document.createElement('div');
  elem.style.color = color;
  document.body.appendChild(elem);
  const rgbColor = getComputedStyle(elem).color;
  document.body.removeChild(elem);

  // Parse the rgb(r, g, b) color that getComputedStyle returns
  const rgb = rgbColor.split('(')[1].split(')')[0].split(',');
  return { r: +rgb[0], g: +rgb[1], b: +rgb[2] };
}

// Easing functions return eased values of x for the range [0, 1] => [0, 1]
export const ease = {
  linear: x => x,
  // Quadratic easing
  in: x => x ** 2,
  out: x => 1 - window.ease.in(1 - x),
  // Sinusoidal easing
  inSin: x => 1 - Math.cos(0.5 * Math.PI * x),
  outSin: x => Math.sin(0.5 * Math.PI * x),
};
<commit_msg>Add async sleep function to helpers<commit_after>// Parse a color by letting CSS parse it
export function parseColor(color) {
  // Make a div, assign a color, and see what CSS parses it as. The div must temporarily be added to
  // the DOM sothat getComputedStyle works.
  const elem = document.createElement('div');
  elem.style.color = color;
  document.body.appendChild(elem);
  const rgbColor = getComputedStyle(elem).color;
  document.body.removeChild(elem);

  // Parse the rgb(r, g, b) color that getComputedStyle returns
  const rgb = rgbColor.split('(')[1].split(')')[0].split(',');
  return { r: +rgb[0], g: +rgb[1], b: +rgb[2] };
}

// Easing functions return eased values of x for the range [0, 1] => [0, 1]
export const ease = {
  linear: x => x,
  // Quadratic easing
  in: x => x ** 2,
  out: x => 1 - window.ease.in(1 - x),
  // Sinusoidal easing
  inSin: x => 1 - Math.cos(0.5 * Math.PI * x),
  outSin: x => Math.sin(0.5 * Math.PI * x),
};

// Sleep for async functions
export function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
<|endoftext|>