<commit_before>const Generator = require('../../lib/generator');
const path = require('path');
const makeConfig = require('./configs');
const { kebabCase } = require('lodash');

module.exports = class AppGenerator extends Generator {
  constructor (args, opts) {
    super(args, opts);

    this.props = {
      name: this.pkg.name || process.cwd().split(path.sep).pop(),
      description: this.pkg.description,
      src: this.pkg.directories && this.pkg.directories.lib
    };

    this.dependencies = [
      '@feathersjs/feathers',
      '@feathersjs/errors',
      '@feathersjs/configuration',
      '@feathersjs/express',
      'serve-favicon',
      'compression',
      'helmet',
      'winston@^3.0.0',
      'cors'
    ];

    this.devDependencies = [
      'nodemon',
      'eslint',
      'axios'
    ];
  }

  prompting () {
    const dependencies = this.dependencies.concat(this.devDependencies)
      .concat([
        '@feathersjs/express',
        '@feathersjs/socketio',
        '@feathersjs/primus'
      ]);
    const prompts = [{
      type: 'list',
      name: 'language',
      message: 'Do you want to use JavaScript or TypeScript?',
      default: 'js',
      choices: [
        { name: 'JavaScript', value: 'js' },
        { name: 'TypeScript', value: 'ts'  }
      ],
    }, {
      name: 'name',
      message: 'Project name',
      when: !this.pkg.name,
      default: this.props.name,
      filter: kebabCase,
      validate (input) {
        // The project name can not be the same as any of the dependencies
        // we are going to install
        const isSelfReferential = dependencies.some(dependency => {
          const separatorIndex = dependency.indexOf('@');
          const end = separatorIndex !== -1 ? separatorIndex : dependency.length;
          const dependencyName = dependency.substring(0, end);

          return dependencyName === input;
        });

        if (isSelfReferential) {
          return `Your project can not be named '${input}' because the '${input}' package will be installed as a project dependency.`;
        }

        return true;
      }
    }, {
      name: 'description',
      message: 'Description',
      when: !this.pkg.description
    }, {
      name: 'src',
      message: 'What folder should the source files live in?',
      default: 'src',
      when: !(this.pkg.directories && this.pkg.directories.lib)
    }, {
      name: 'packager',
      type: 'list',
      message: 'Which package manager are you using (has to be installed globally)?',
      default: 'npm',
      choices: [
        { name: 'npm', value: 'npm'   },
        { name: 'Yarn', value: 'yarn' }
      ]
    }, {
      type: 'checkbox',
      name: 'providers',
      message: 'What type of API are you making?',
      choices: [
        { name: 'REST', value: 'rest',     checked: true },
        { name: 'Realtime via Socket.io', value: 'socketio', checked: true },
        { name: 'Realtime via Primus', value: 'primus',                 }
      ],
      validate (input) {
        if (input.indexOf('primus') !== -1 && input.indexOf('socketio') !== -1) {
          return 'You can only pick SocketIO or Primus, not both.';
        }

        return true;
      }
    }, {
      type: 'list',
      name: 'tester',
      message: 'Which testing framework do you prefer?',
      default: 'mocha',
      choices: [
        { name: 'Mocha + assert', value: 'mocha' },
        { name: 'Jest', value: 'jest'  }
      ]
    }, {
      name: 'authentication',
      message: 'This app uses authentication',
      type: 'confirm',
      default: true
    }];

    return this.prompt(prompts).then(props => {
      this.props = Object.assign(this.props, props);
    });
  }

  writing () {
    const props = this.props;
    const pkg = this.pkg = makeConfig.package(this);
    const context = Object.assign({}, props, {
      hasProvider (name) {
        return props.providers.indexOf(name) !== -1;
      }
    });

    // Static content for the root folder (including dotfiles)
    this.fs.copy(this.templatePath('..', 'static'), this.destinationPath());
    this.fs.copy(this.templatePath('..', 'static', '.*'), this.destinationPath());
    // Static content for the directories.lib folder
    this.fs.copy(this.templatePath('src'), this.destinationPath(props.src));
    // This hack is necessary because NPM does not publish `.gitignore` files
    this.fs.copy(this.templatePath('_gitignore'), this.destinationPath('', '.gitignore'));

    this.fs.copyTpl(
      this.templatePath('README.md'),
      this.destinationPath('', 'README.md'),
      context
    );

    this.fs.copyTpl(
      this.srcTemplatePath('app'),
      this.srcDestinationPath(this.libDirectory, 'app'),
      context
    );

    this.fs.copyTpl(
      this.srcTemplatePath(`app.test.${props.tester}`),
      this.srcDestinationPath(this.testDirectory, 'app.test'),
      context
    );

    this.fs.writeJSON(
      this.destinationPath('package.json'),
      pkg
    );

    if (this.isTypescript) {
      this.fs.writeJSON(
        this.destinationPath('tsconfig.json'),
        makeConfig.tsconfig(this)
      );

      if (props.tester === 'jest') {
        this.fs.copyTpl(
          this.templatePath('jest.config.js'),
          this.destinationPath('jest.config.js'),
          context
        );
      }
    } else {
      this.fs.writeJSON(
        this.destinationPath('.eslintrc.json'),
        makeConfig.eslintrc(this)
      );
    }

    this.fs.writeJSON(
      this.destinationPath(this.configDirectory, 'default.json'),
      makeConfig.configDefault(this)
    );

    this.fs.writeJSON(
      this.destinationPath(this.configDirectory, 'production.json'),
      makeConfig.configProduction(this)
    );

    if (props.authentication) {
      // Create the users service
      this.composeWith(require.resolve('../authentication'), {
        props: { tester: props.tester }
      });
    }
  }

  install () {
    this.props.providers.forEach(provider => {
      const type = provider === 'rest' ? 'express' : provider;

      this.dependencies.push(`@feathersjs/${type}`);

      if (provider === 'primus') {
        this.dependencies.push('ws');
      }
    });

    this._packagerInstall(this.dependencies, {
      save: true
    });

    if (this.isTypescript) {
      const excluded = [
        'eslint',
        'nodemon@^1.18.7',
      ];
      this.devDependencies = this.devDependencies.concat([
        '@types/compression',
        '@types/cors',
        '@types/helmet',
        '@types/serve-favicon',
        'shx',
        'ts-node-dev',
        'tslint',
        'typescript',
        `@types/${this.props.tester}`,
        `ts-${this.props.tester}`,
      ]).filter(item => !excluded.includes(item));
    }

    this.devDependencies.push(this.props.tester);

    this._packagerInstall(this.devDependencies, {
      saveDev: true
    });
  }
};
<commit_msg>Set packager version in choices value (#456)<commit_after>const Generator = require('../../lib/generator');
const path = require('path');
const makeConfig = require('./configs');
const { kebabCase } = require('lodash');

module.exports = class AppGenerator extends Generator {
  constructor (args, opts) {
    super(args, opts);

    this.props = {
      name: this.pkg.name || process.cwd().split(path.sep).pop(),
      description: this.pkg.description,
      src: this.pkg.directories && this.pkg.directories.lib
    };

    this.dependencies = [
      '@feathersjs/feathers',
      '@feathersjs/errors',
      '@feathersjs/configuration',
      '@feathersjs/express',
      'serve-favicon',
      'compression',
      'helmet',
      'winston@^3.0.0',
      'cors'
    ];

    this.devDependencies = [
      'nodemon',
      'eslint',
      'axios'
    ];
  }

  prompting () {
    const dependencies = this.dependencies.concat(this.devDependencies)
      .concat([
        '@feathersjs/express',
        '@feathersjs/socketio',
        '@feathersjs/primus'
      ]);
    const prompts = [{
      type: 'list',
      name: 'language',
      message: 'Do you want to use JavaScript or TypeScript?',
      default: 'js',
      choices: [
        { name: 'JavaScript', value: 'js' },
        { name: 'TypeScript', value: 'ts'  }
      ],
    }, {
      name: 'name',
      message: 'Project name',
      when: !this.pkg.name,
      default: this.props.name,
      filter: kebabCase,
      validate (input) {
        // The project name can not be the same as any of the dependencies
        // we are going to install
        const isSelfReferential = dependencies.some(dependency => {
          const separatorIndex = dependency.indexOf('@');
          const end = separatorIndex !== -1 ? separatorIndex : dependency.length;
          const dependencyName = dependency.substring(0, end);

          return dependencyName === input;
        });

        if (isSelfReferential) {
          return `Your project can not be named '${input}' because the '${input}' package will be installed as a project dependency.`;
        }

        return true;
      }
    }, {
      name: 'description',
      message: 'Description',
      when: !this.pkg.description
    }, {
      name: 'src',
      message: 'What folder should the source files live in?',
      default: 'src',
      when: !(this.pkg.directories && this.pkg.directories.lib)
    }, {
      name: 'packager',
      type: 'list',
      message: 'Which package manager are you using (has to be installed globally)?',
      default: 'npm',
      choices: [
        { name: 'npm', value: 'npm@>= 3.0.0'   },
        { name: 'Yarn', value: 'yarn@>= 0.18.0' }
      ]
    }, {
      type: 'checkbox',
      name: 'providers',
      message: 'What type of API are you making?',
      choices: [
        { name: 'REST', value: 'rest',     checked: true },
        { name: 'Realtime via Socket.io', value: 'socketio', checked: true },
        { name: 'Realtime via Primus', value: 'primus',                 }
      ],
      validate (input) {
        if (input.indexOf('primus') !== -1 && input.indexOf('socketio') !== -1) {
          return 'You can only pick SocketIO or Primus, not both.';
        }

        return true;
      }
    }, {
      type: 'list',
      name: 'tester',
      message: 'Which testing framework do you prefer?',
      default: 'mocha',
      choices: [
        { name: 'Mocha + assert', value: 'mocha' },
        { name: 'Jest', value: 'jest'  }
      ]
    }, {
      name: 'authentication',
      message: 'This app uses authentication',
      type: 'confirm',
      default: true
    }];

    return this.prompt(prompts).then(props => {
      this.props = Object.assign(this.props, props);
    });
  }

  writing () {
    const props = this.props;
    const pkg = this.pkg = makeConfig.package(this);
    const context = Object.assign({}, props, {
      hasProvider (name) {
        return props.providers.indexOf(name) !== -1;
      }
    });

    // Static content for the root folder (including dotfiles)
    this.fs.copy(this.templatePath('..', 'static'), this.destinationPath());
    this.fs.copy(this.templatePath('..', 'static', '.*'), this.destinationPath());
    // Static content for the directories.lib folder
    this.fs.copy(this.templatePath('src'), this.destinationPath(props.src));
    // This hack is necessary because NPM does not publish `.gitignore` files
    this.fs.copy(this.templatePath('_gitignore'), this.destinationPath('', '.gitignore'));

    this.fs.copyTpl(
      this.templatePath('README.md'),
      this.destinationPath('', 'README.md'),
      context
    );

    this.fs.copyTpl(
      this.srcTemplatePath('app'),
      this.srcDestinationPath(this.libDirectory, 'app'),
      context
    );

    this.fs.copyTpl(
      this.srcTemplatePath(`app.test.${props.tester}`),
      this.srcDestinationPath(this.testDirectory, 'app.test'),
      context
    );

    this.fs.writeJSON(
      this.destinationPath('package.json'),
      pkg
    );

    if (this.isTypescript) {
      this.fs.writeJSON(
        this.destinationPath('tsconfig.json'),
        makeConfig.tsconfig(this)
      );

      if (props.tester === 'jest') {
        this.fs.copyTpl(
          this.templatePath('jest.config.js'),
          this.destinationPath('jest.config.js'),
          context
        );
      }
    } else {
      this.fs.writeJSON(
        this.destinationPath('.eslintrc.json'),
        makeConfig.eslintrc(this)
      );
    }

    this.fs.writeJSON(
      this.destinationPath(this.configDirectory, 'default.json'),
      makeConfig.configDefault(this)
    );

    this.fs.writeJSON(
      this.destinationPath(this.configDirectory, 'production.json'),
      makeConfig.configProduction(this)
    );

    if (props.authentication) {
      // Create the users service
      this.composeWith(require.resolve('../authentication'), {
        props: { tester: props.tester }
      });
    }
  }

  install () {
    this.props.providers.forEach(provider => {
      const type = provider === 'rest' ? 'express' : provider;

      this.dependencies.push(`@feathersjs/${type}`);

      if (provider === 'primus') {
        this.dependencies.push('ws');
      }
    });

    this._packagerInstall(this.dependencies, {
      save: true
    });

    if (this.isTypescript) {
      const excluded = [
        'eslint',
        'nodemon@^1.18.7',
      ];
      this.devDependencies = this.devDependencies.concat([
        '@types/compression',
        '@types/cors',
        '@types/helmet',
        '@types/serve-favicon',
        'shx',
        'ts-node-dev',
        'tslint',
        'typescript',
        `@types/${this.props.tester}`,
        `ts-${this.props.tester}`,
      ]).filter(item => !excluded.includes(item));
    }

    this.devDependencies.push(this.props.tester);

    this._packagerInstall(this.devDependencies, {
      saveDev: true
    });
  }
};
<|endoftext|>


<commit_before>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');

module.exports = yeoman.generators.Base.extend({
  prompting: function() {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the sweet ' + chalk.red('generator-atomic-reactor') + ' generator!'
    ));

    var prompts = [{
      type: 'confirm',
      name: 'someOption',
      message: 'Would you like to enable this option?',
      default: true,
    },
  ];

    this.prompt(prompts, function(props) {
      this.props = props;

      // To access props later use this.props.someOption;

      done();
    }.bind(this));
  },

  writing: function() {
    this.fs.copy(
      this.templatePath('dummyfile.txt'),
      this.destinationPath('dummyfile.txt')
    );
  },

  install: function() {
    this.installDependencies();
  },
});
<commit_msg>change greeting<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');

module.exports = yeoman.generators.Base.extend({
  prompting: function() {
    var done = this.async();

    this.log(yosay(
      'Welcome to the nuclear ' + chalk.red('generator-atomic-reactor')
    ));

    var prompts = [{
      type: 'confirm',
      name: 'someOption',
      message: 'Would you like to enable this option?',
      default: true,
    },
  ];

    this.prompt(prompts, function(props) {
      this.props = props;

      // To access props later use this.props.someOption;

      done();
    }.bind(this));
  },

  writing: function() {
    this.fs.copy(
      this.templatePath('dummyfile.txt'),
      this.destinationPath('dummyfile.txt')
    );
  },

  install: function() {
    this.installDependencies();
  },
});
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const Generator = require('yeoman-generator');
const chalk = require('chalk');
const yosay = require('yosay');
const _ = require('lodash');
const askName = require('inquirer-npm-name');
const extend = require('deep-extend');
const mkdirp = require('mkdirp');
const githubUsername = require('github-username');
const parseAuthor = require('parse-author');

module.exports = Generator.extend({
	initializing() {
		// Have Yeoman greet the user.
		this.log(yosay('Welcome to the ' + chalk.red('NodeCG bundle') + ' generator!'));

		this.pkg = this.fs.readJSON(this.destinationPath('package.json'), {});

		// Pre set the default props from the information we have at this point
		this.props = {
			name: this.pkg.name,
			description: this.pkg.description,
			version: this.pkg.version,
			homepage: this.pkg.homepage
		};

		if (_.isObject(this.pkg.author)) {
			this.props.authorName = this.pkg.author.name;
			this.props.authorEmail = this.pkg.author.email;
			this.props.authorUrl = this.pkg.author.url;
		} else if (_.isString(this.pkg.author)) {
			const info = parseAuthor(this.pkg.author);
			this.props.authorName = info.name;
			this.props.authorEmail = info.email;
			this.props.authorUrl = info.url;
		}
	},

	prompting: {
		askForModuleName() {
			return askName({
				name: 'name',
				message: 'Your bundle Name',
				default: _.kebabCase(path.basename(process.cwd())),
				filter: _.kebabCase,
				validate(str) {
					return str.length > 0;
				}
			}, this).then(({name}) => {
				this.props.name = name;
			});
		},

		askFor() {
			const done = this.async();

			const prompts = [{
				name: 'description',
				message: 'Description',
				when: !this.props.description
			}, {
				name: 'homepage',
				message: 'Project homepage url',
				when: !this.props.homepage
			}, {
				name: 'authorName',
				message: 'Author\'s Name',
				when: !this.props.authorName,
				default: this.user.git.name(),
				store: true
			}, {
				name: 'authorEmail',
				message: 'Author\'s Email',
				when: !this.props.authorEmail,
				default: this.user.git.email(),
				store: true
			}, {
				name: 'authorUrl',
				message: 'Author\'s Homepage',
				when: !this.props.authorUrl,
				store: true
			}, {
				name: 'keywords',
				message: 'Package keywords (comma to split)',
				when: !this.pkg.keywords,
				filter(words) {
					return words.split(/\s*,\s*/g);
				}
			}, {
				name: 'compatibleRange',
				message: 'What semver range of NodeCG versions is this bundle compatible with?',
				type: 'input',
				default: '~0.8.0'
			}, {
				name: 'dashboardPanel',
				message: 'Would you like to make a dashboard panel for your bundle?',
				type: 'confirm'
			}, {
				name: 'graphic',
				message: 'Would you like to make a graphic for your bundle?',
				type: 'confirm'
			}, {
				name: 'extension',
				message: 'Would you like to add an extension to your bundle?',
				type: 'confirm'
			}];

			this.prompt(prompts).then(props => {
				this.props = extend(this.props, props);
				done();
			});
		},

		askForGithubAccount() {
			const done = this.async();

			githubUsername(this.props.authorEmail, (err, username) => {
				if (err) {
					username = username || '';
				}

				this.prompt({
					name: 'githubAccount',
					message: 'GitHub username or organization',
					default: username
				}).then(prompt => {
					this.props.githubAccount = prompt.githubAccount;
					done();
				});
			});
		}
	},

	writing() {
		// Re-read the content at this point because a composed generator might modify it.
		const currentPkg = this.fs.readJSON(this.destinationPath('package.json'), {});

		const pkg = extend({
			name: _.kebabCase(this.props.name),
			version: '0.0.0',
			description: this.props.description,
			homepage: this.props.homepage,
			author: {
				name: this.props.authorName,
				email: this.props.authorEmail,
				url: this.props.authorUrl
			},
			files: [
				'dashboard',
				'graphics',
				'extension.js',
				'extension'
			],
			keywords: [
				'nodecg-bundle'
			],
			nodecg: {
				compatibleRange: this.props.compatibleRange
			}
		}, currentPkg);

		// Combine the keywords
		if (this.props.keywords) {
			pkg.keywords = _.uniq(this.props.keywords.concat(pkg.keywords));
		}

		// Let's extend package.json so we're not overwriting user previous fields
		this.fs.writeJSON(this.destinationPath('package.json'), pkg);

		// Populate and write the readme template
		if (!this.fs.exists(this.destinationPath('README.md'))) {
			this.fs.copyTpl(
				this.templatePath('README.md'),
				this.destinationPath('README.md'),
				{
					name: this.props.name,
					compatibleRange: this.props.compatibleRange
				}
			);
		}

		// Replace the .gitignore from node:git with our own.
		this.fs.write(this.destinationPath('.gitignore'), 'node_modules\ncoverage\nbower_components');
	},

	default() {
		if (path.basename(this.destinationPath()) !== this.props.name) {
			this.log(
				'Your bundle must be inside a folder named ' + this.props.name + '\n' +
				'I\'ll automatically create this folder.'
			);
			mkdirp(this.props.name);
			this.destinationRoot(this.destinationPath(this.props.name));
		}

		this.composeWith(require.resolve('generator-node/generators/git'), {
			name: this.props.name,
			githubAccount: this.props.githubAccount
		});

		if (!this.pkg.license) {
			this.composeWith(require.resolve('generator-license/app'), {
				name: this.props.authorName,
				email: this.props.authorEmail,
				website: this.props.authorUrl
			});
		}

		if (this.props.dashboardPanel) {
			this.composeWith(require.resolve('./../panel'));
		}

		if (this.props.graphic) {
			this.composeWith(require.resolve('./../graphic'));
		}

		if (this.props.extension) {
			this.composeWith(require.resolve('./../extension'));
		}
	}
});
<commit_msg>feat: update default compatibleRange to ~0.9.0<commit_after>'use strict';

const path = require('path');
const Generator = require('yeoman-generator');
const chalk = require('chalk');
const yosay = require('yosay');
const _ = require('lodash');
const askName = require('inquirer-npm-name');
const extend = require('deep-extend');
const mkdirp = require('mkdirp');
const githubUsername = require('github-username');
const parseAuthor = require('parse-author');

module.exports = Generator.extend({
	initializing() {
		// Have Yeoman greet the user.
		this.log(yosay('Welcome to the ' + chalk.red('NodeCG bundle') + ' generator!'));

		this.pkg = this.fs.readJSON(this.destinationPath('package.json'), {});

		// Pre set the default props from the information we have at this point
		this.props = {
			name: this.pkg.name,
			description: this.pkg.description,
			version: this.pkg.version,
			homepage: this.pkg.homepage
		};

		if (_.isObject(this.pkg.author)) {
			this.props.authorName = this.pkg.author.name;
			this.props.authorEmail = this.pkg.author.email;
			this.props.authorUrl = this.pkg.author.url;
		} else if (_.isString(this.pkg.author)) {
			const info = parseAuthor(this.pkg.author);
			this.props.authorName = info.name;
			this.props.authorEmail = info.email;
			this.props.authorUrl = info.url;
		}
	},

	prompting: {
		askForModuleName() {
			return askName({
				name: 'name',
				message: 'Your bundle Name',
				default: _.kebabCase(path.basename(process.cwd())),
				filter: _.kebabCase,
				validate(str) {
					return str.length > 0;
				}
			}, this).then(({name}) => {
				this.props.name = name;
			});
		},

		askFor() {
			const done = this.async();

			const prompts = [{
				name: 'description',
				message: 'Description',
				when: !this.props.description
			}, {
				name: 'homepage',
				message: 'Project homepage url',
				when: !this.props.homepage
			}, {
				name: 'authorName',
				message: 'Author\'s Name',
				when: !this.props.authorName,
				default: this.user.git.name(),
				store: true
			}, {
				name: 'authorEmail',
				message: 'Author\'s Email',
				when: !this.props.authorEmail,
				default: this.user.git.email(),
				store: true
			}, {
				name: 'authorUrl',
				message: 'Author\'s Homepage',
				when: !this.props.authorUrl,
				store: true
			}, {
				name: 'keywords',
				message: 'Package keywords (comma to split)',
				when: !this.pkg.keywords,
				filter(words) {
					return words.split(/\s*,\s*/g);
				}
			}, {
				name: 'compatibleRange',
				message: 'What semver range of NodeCG versions is this bundle compatible with?',
				type: 'input',
				default: '~0.9.0'
			}, {
				name: 'dashboardPanel',
				message: 'Would you like to make a dashboard panel for your bundle?',
				type: 'confirm'
			}, {
				name: 'graphic',
				message: 'Would you like to make a graphic for your bundle?',
				type: 'confirm'
			}, {
				name: 'extension',
				message: 'Would you like to add an extension to your bundle?',
				type: 'confirm'
			}];

			this.prompt(prompts).then(props => {
				this.props = extend(this.props, props);
				done();
			});
		},

		askForGithubAccount() {
			const done = this.async();

			githubUsername(this.props.authorEmail, (err, username) => {
				if (err) {
					username = username || '';
				}

				this.prompt({
					name: 'githubAccount',
					message: 'GitHub username or organization',
					default: username
				}).then(prompt => {
					this.props.githubAccount = prompt.githubAccount;
					done();
				});
			});
		}
	},

	writing() {
		// Re-read the content at this point because a composed generator might modify it.
		const currentPkg = this.fs.readJSON(this.destinationPath('package.json'), {});

		const pkg = extend({
			name: _.kebabCase(this.props.name),
			version: '0.0.0',
			description: this.props.description,
			homepage: this.props.homepage,
			author: {
				name: this.props.authorName,
				email: this.props.authorEmail,
				url: this.props.authorUrl
			},
			files: [
				'dashboard',
				'graphics',
				'extension.js',
				'extension'
			],
			keywords: [
				'nodecg-bundle'
			],
			nodecg: {
				compatibleRange: this.props.compatibleRange
			}
		}, currentPkg);

		// Combine the keywords
		if (this.props.keywords) {
			pkg.keywords = _.uniq(this.props.keywords.concat(pkg.keywords));
		}

		// Let's extend package.json so we're not overwriting user previous fields
		this.fs.writeJSON(this.destinationPath('package.json'), pkg);

		// Populate and write the readme template
		if (!this.fs.exists(this.destinationPath('README.md'))) {
			this.fs.copyTpl(
				this.templatePath('README.md'),
				this.destinationPath('README.md'),
				{
					name: this.props.name,
					compatibleRange: this.props.compatibleRange
				}
			);
		}

		// Replace the .gitignore from node:git with our own.
		this.fs.write(this.destinationPath('.gitignore'), 'node_modules\ncoverage\nbower_components');
	},

	default() {
		if (path.basename(this.destinationPath()) !== this.props.name) {
			this.log(
				'Your bundle must be inside a folder named ' + this.props.name + '\n' +
				'I\'ll automatically create this folder.'
			);
			mkdirp(this.props.name);
			this.destinationRoot(this.destinationPath(this.props.name));
		}

		this.composeWith(require.resolve('generator-node/generators/git'), {
			name: this.props.name,
			githubAccount: this.props.githubAccount
		});

		if (!this.pkg.license) {
			this.composeWith(require.resolve('generator-license/app'), {
				name: this.props.authorName,
				email: this.props.authorEmail,
				website: this.props.authorUrl
			});
		}

		if (this.props.dashboardPanel) {
			this.composeWith(require.resolve('./../panel'));
		}

		if (this.props.graphic) {
			this.composeWith(require.resolve('./../graphic'));
		}

		if (this.props.extension) {
			this.composeWith(require.resolve('./../extension'));
		}
	}
});
<|endoftext|>


<commit_before>/**
 * Visual Blocks Language
 *
 * Copyright 2012 Google Inc.
 * http://code.google.com/p/blockly/
 *
 * 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.
 */

/**
 * @fileoverview Generating Dart for text blocks.
 * @author fraser@google.com (Neil Fraser)
 * Due to the frequency of long strings, the 80-column wrap rule need not apply
 * to language files.
 */

Blockly.Dart = Blockly.Generator.get('Dart');

Blockly.Dart.text = function() {
  // Text value.
  var code = Blockly.Dart.quote_(this.getTitleText('TEXT'));
  return [code, Blockly.Dart.ORDER_ATOMIC];
};

Blockly.Dart.text_join = function() {
  // Create a string made up of any number of elements of any type.
  var code;
  if (this.itemCount_ == 0) {
    return ['\'\'', Blockly.Dart.ORDER_ATOMIC];
  } else if (this.itemCount_ == 1) {
    var argument0 = Blockly.Dart.valueToCode(this, 'ADD0',
        Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\'';
    code = argument0 + '.toString()';
    return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
  } else if (this.itemCount_ == 2) {
    var argument0 = Blockly.Dart.valueToCode(this, 'ADD0',
        Blockly.Dart.ORDER_NONE) || '\'\'';
    var argument1 = Blockly.Dart.valueToCode(this, 'ADD0',
        Blockly.Dart.ORDER_NONE) || '\'\'';
    code = argument0 + '.toString() + ' + argument1 + '.toString()';
    return [code, Blockly.Dart.ORDER_ADDITIVE];
  } else {
    code = [];
    code[0] = 'new StringBuffer(' + (Blockly.Dart.valueToCode(this, 'ADD0',
        Blockly.Dart.ORDER_NONE) || '\'\'') + ')';
    for (var n = 1; n < this.itemCount_; n++) {
      code[n] = '.add(' + (Blockly.Dart.valueToCode(this, 'ADD' + n,
          Blockly.Dart.ORDER_NONE) || '\'\'') + ')';
    }
    code = code.join('') + '.toString()';
    return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
  }
};

Blockly.Dart.text_length = function() {
  // String length.
  var argument0 = Blockly.Dart.valueToCode(this, 'VALUE',
      Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\'';
  return [argument0 + '.length', Blockly.Dart.ORDER_UNARY_POSTFIX];
};

Blockly.Dart.text_isEmpty = function() {
  // Is the string null?
  var argument0 = Blockly.Dart.valueToCode(this, 'VALUE',
      Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\'';
  return [argument0 + '.isEmpty()', Blockly.Dart.ORDER_UNARY_POSTFIX];
};

Blockly.Dart.text_endString = function() {
  // Return a leading or trailing substring.
  var first = this.getTitleValue('END') == 'FIRST';
  var code;
  if (first) {
    var argument0 = Blockly.Dart.valueToCode(this, 'NUM',
        Blockly.Dart.ORDER_NONE) || '1';
    var argument1 = Blockly.Dart.valueToCode(this, 'TEXT',
        Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\'';
    code = argument1 + '.substring(0, ' + argument0 + ')';
  } else {
    if (!Blockly.Dart.definitions_['text_tailString']) {
      var functionName = Blockly.Dart.variableDB_.getDistinctName('text_tailString',
          Blockly.Generator.NAME_TYPE);
      Blockly.Dart.text_endString.text_tailString = functionName;
      var func = [];
      func.push('String ' + functionName + '(n, myString) {');
      func.push('  // Return a trailing substring of n characters.');
      func.push('  return myString.substring(myString.length - n);');
      func.push('}');
      Blockly.Dart.definitions_['text_tailString'] = func.join('\n');
    }
    var argument0 = Blockly.Dart.valueToCode(this, 'NUM',
        Blockly.Dart.ORDER_NONE) || '1';
    var argument1 = Blockly.Dart.valueToCode(this, 'TEXT',
        Blockly.Dart.ORDER_NONE) || '\'\'';
    code = Blockly.Dart.text_endString.text_tailString +
        '(' + argument0 + ', ' + argument1 + ')';
  }
  return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};

Blockly.Dart.text_indexOf = function() {
  // Search the text for a substring.
  var operator = this.getTitleValue('END') == 'FIRST' ? 'indexOf' : 'lastIndexOf';
  var argument0 = Blockly.Dart.valueToCode(this, 'FIND',
      Blockly.Dart.ORDER_NONE) || '\'\'';
  var argument1 = Blockly.Dart.valueToCode(this, 'VALUE',
      Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\'';
  var code = argument1 + '.' + operator + '(' + argument0 + ') + 1';
  return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};

Blockly.Dart.text_charAt = function() {
  // Get letter at index.
  var argument0 = Blockly.Dart.valueToCode(this, 'AT',
      Blockly.Dart.ORDER_NONE) || '1';
  var argument1 = Blockly.Dart.valueToCode(this, 'VALUE',
      Blockly.Dart.ORDER_UNARY_POSTFIX) || '[]';
  // Blockly uses one-based arrays.
  if (argument0.match(/^\d+$/)) {
    // If the index is a naked number, decrement it right now.
    argument0 = parseInt(argument0, 10) - 1;
  } else {
    // If the index is dynamic, decrement it in code.
    argument0 += ' - 1';
  }
  var code = argument1 + '[' + argument0 + ']';
  return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};

Blockly.Dart.text_changeCase = function() {
  // Change capitalization.
  var mode = this.getTitleValue('CASE');
  var operator = Blockly.Dart.text_changeCase.OPERATORS[mode];
  var code;
  if (operator) {
    // Upper and lower case are functions built into Dart.
    var argument0 = Blockly.Dart.valueToCode(this, 'TEXT',
        Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\'';
    code = argument0 + operator;
  } else {
    if (!Blockly.Dart.definitions_['toTitleCase']) {
      // Title case is not a native Dart function.  Define one.
      var functionName = Blockly.Dart.variableDB_.getDistinctName('text_toTitleCase',
          Blockly.Generator.NAME_TYPE);
      Blockly.Dart.text_changeCase.toTitleCase = functionName;
      var func = [];
      func.push('String ' + functionName + '(str) {');
      func.push('  RegExp exp = const RegExp(@"(\\S+)");');
      func.push('  List<String> list = str.split(exp);');
      func.push('  String title = \'\';');
      func.push('  for (String part in list) {');
      func.push('    if (part.length > 0) {');
      func.push('      title += part[0].toUpperCase();');
      func.push('      if (part.length > 0) {');
      func.push('        title += part.substring(1).toLowerCase();');
      func.push('      }');
      func.push('    }');
      func.push('  }');
      func.push('  return title;');
      func.push('}');
      Blockly.Dart.definitions_['toTitleCase'] = func.join('\n');
    }
    var argument0 = Blockly.Dart.valueToCode(this, 'TEXT',
        Blockly.Dart.ORDER_NONE) || '\'\'';
    code = Blockly.Dart.text_changeCase.toTitleCase + '(' + argument0 + ')';
  }
  return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};

Blockly.Dart.text_changeCase.OPERATORS = {
  UPPERCASE: '.toUpperCase()',
  LOWERCASE: '.toLowerCase()',
  TITLECASE: null
};

Blockly.Dart.text_trim = function() {
  // Trim spaces.
  var mode = this.getTitleValue('MODE');
  var operator = Blockly.Dart.text_trim.OPERATORS[mode];
  var argument0 = Blockly.Dart.valueToCode(this, 'TEXT',
      Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\'';
  return [argument0 + operator, Blockly.Dart.ORDER_UNARY_POSTFIX];
};

Blockly.Dart.text_trim.OPERATORS = {
  LEFT: '.replaceFirst(new RegExp(@"^\\s+"), \'\')',
  RIGHT: '.replaceFirst(new RegExp(@"\\s+$"), \'\')',
  BOTH: '.trim()'
};

Blockly.Dart.text_print = function() {
  // Print statement.
  var argument0 = Blockly.Dart.valueToCode(this, 'TEXT',
      Blockly.Dart.ORDER_NONE) || '\'\'';
  return 'print(' + argument0 + ');\n';
};

Blockly.Dart.text_prompt = function() {
  // Prompt function.
  Blockly.Dart.definitions_['import_dart_html'] = '#import(\'dart:html\');';
  var msg = Blockly.Dart.quote_(this.getTitleValue('TEXT'));
  var code = 'window.prompt(' + msg + ', \'\')';
  var toNumber = this.getTitleValue('TYPE') == 'NUMBER';
  if (toNumber) {
    code = 'Math.parseDouble(' + code + ')';
  }
  return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};
<commit_msg>Update Dart generator; Dart no longer accepts string concatenation with '+'.<commit_after>/**
 * Visual Blocks Language
 *
 * Copyright 2012 Google Inc.
 * http://code.google.com/p/blockly/
 *
 * 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.
 */

/**
 * @fileoverview Generating Dart for text blocks.
 * @author fraser@google.com (Neil Fraser)
 * Due to the frequency of long strings, the 80-column wrap rule need not apply
 * to language files.
 */

Blockly.Dart = Blockly.Generator.get('Dart');

Blockly.Dart.text = function() {
  // Text value.
  var code = Blockly.Dart.quote_(this.getTitleText('TEXT'));
  return [code, Blockly.Dart.ORDER_ATOMIC];
};

Blockly.Dart.text_join = function() {
  // Create a string made up of any number of elements of any type.
  var code;
  if (this.itemCount_ == 0) {
    return ['\'\'', Blockly.Dart.ORDER_ATOMIC];
  } else if (this.itemCount_ == 1) {
    var argument0 = Blockly.Dart.valueToCode(this, 'ADD0',
        Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\'';
    code = argument0 + '.toString()';
    return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
  } else {
    code = [];
    code[0] = 'new StringBuffer(' + (Blockly.Dart.valueToCode(this, 'ADD0',
        Blockly.Dart.ORDER_NONE) || '\'\'') + ')';
    for (var n = 1; n < this.itemCount_; n++) {
      code[n] = '.add(' + (Blockly.Dart.valueToCode(this, 'ADD' + n,
          Blockly.Dart.ORDER_NONE) || '\'\'') + ')';
    }
    code = code.join('') + '.toString()';
    return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
  }
};

Blockly.Dart.text_length = function() {
  // String length.
  var argument0 = Blockly.Dart.valueToCode(this, 'VALUE',
      Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\'';
  return [argument0 + '.length', Blockly.Dart.ORDER_UNARY_POSTFIX];
};

Blockly.Dart.text_isEmpty = function() {
  // Is the string null?
  var argument0 = Blockly.Dart.valueToCode(this, 'VALUE',
      Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\'';
  return [argument0 + '.isEmpty()', Blockly.Dart.ORDER_UNARY_POSTFIX];
};

Blockly.Dart.text_endString = function() {
  // Return a leading or trailing substring.
  var first = this.getTitleValue('END') == 'FIRST';
  var code;
  if (first) {
    var argument0 = Blockly.Dart.valueToCode(this, 'NUM',
        Blockly.Dart.ORDER_NONE) || '1';
    var argument1 = Blockly.Dart.valueToCode(this, 'TEXT',
        Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\'';
    code = argument1 + '.substring(0, ' + argument0 + ')';
  } else {
    if (!Blockly.Dart.definitions_['text_tailString']) {
      var functionName = Blockly.Dart.variableDB_.getDistinctName('text_tailString',
          Blockly.Generator.NAME_TYPE);
      Blockly.Dart.text_endString.text_tailString = functionName;
      var func = [];
      func.push('String ' + functionName + '(n, myString) {');
      func.push('  // Return a trailing substring of n characters.');
      func.push('  return myString.substring(myString.length - n);');
      func.push('}');
      Blockly.Dart.definitions_['text_tailString'] = func.join('\n');
    }
    var argument0 = Blockly.Dart.valueToCode(this, 'NUM',
        Blockly.Dart.ORDER_NONE) || '1';
    var argument1 = Blockly.Dart.valueToCode(this, 'TEXT',
        Blockly.Dart.ORDER_NONE) || '\'\'';
    code = Blockly.Dart.text_endString.text_tailString +
        '(' + argument0 + ', ' + argument1 + ')';
  }
  return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};

Blockly.Dart.text_indexOf = function() {
  // Search the text for a substring.
  var operator = this.getTitleValue('END') == 'FIRST' ? 'indexOf' : 'lastIndexOf';
  var argument0 = Blockly.Dart.valueToCode(this, 'FIND',
      Blockly.Dart.ORDER_NONE) || '\'\'';
  var argument1 = Blockly.Dart.valueToCode(this, 'VALUE',
      Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\'';
  var code = argument1 + '.' + operator + '(' + argument0 + ') + 1';
  return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};

Blockly.Dart.text_charAt = function() {
  // Get letter at index.
  var argument0 = Blockly.Dart.valueToCode(this, 'AT',
      Blockly.Dart.ORDER_NONE) || '1';
  var argument1 = Blockly.Dart.valueToCode(this, 'VALUE',
      Blockly.Dart.ORDER_UNARY_POSTFIX) || '[]';
  // Blockly uses one-based arrays.
  if (argument0.match(/^\d+$/)) {
    // If the index is a naked number, decrement it right now.
    argument0 = parseInt(argument0, 10) - 1;
  } else {
    // If the index is dynamic, decrement it in code.
    argument0 += ' - 1';
  }
  var code = argument1 + '[' + argument0 + ']';
  return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};

Blockly.Dart.text_changeCase = function() {
  // Change capitalization.
  var mode = this.getTitleValue('CASE');
  var operator = Blockly.Dart.text_changeCase.OPERATORS[mode];
  var code;
  if (operator) {
    // Upper and lower case are functions built into Dart.
    var argument0 = Blockly.Dart.valueToCode(this, 'TEXT',
        Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\'';
    code = argument0 + operator;
  } else {
    if (!Blockly.Dart.definitions_['toTitleCase']) {
      // Title case is not a native Dart function.  Define one.
      var functionName = Blockly.Dart.variableDB_.getDistinctName('text_toTitleCase',
          Blockly.Generator.NAME_TYPE);
      Blockly.Dart.text_changeCase.toTitleCase = functionName;
      var func = [];
      func.push('String ' + functionName + '(str) {');
      func.push('  RegExp exp = const RegExp(@"(\\S+)");');
      func.push('  List<String> list = str.split(exp);');
      func.push('  String title = \'\';');
      func.push('  for (String part in list) {');
      func.push('    if (part.length > 0) {');
      func.push('      title += part[0].toUpperCase();');
      func.push('      if (part.length > 0) {');
      func.push('        title += part.substring(1).toLowerCase();');
      func.push('      }');
      func.push('    }');
      func.push('  }');
      func.push('  return title;');
      func.push('}');
      Blockly.Dart.definitions_['toTitleCase'] = func.join('\n');
    }
    var argument0 = Blockly.Dart.valueToCode(this, 'TEXT',
        Blockly.Dart.ORDER_NONE) || '\'\'';
    code = Blockly.Dart.text_changeCase.toTitleCase + '(' + argument0 + ')';
  }
  return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};

Blockly.Dart.text_changeCase.OPERATORS = {
  UPPERCASE: '.toUpperCase()',
  LOWERCASE: '.toLowerCase()',
  TITLECASE: null
};

Blockly.Dart.text_trim = function() {
  // Trim spaces.
  var mode = this.getTitleValue('MODE');
  var operator = Blockly.Dart.text_trim.OPERATORS[mode];
  var argument0 = Blockly.Dart.valueToCode(this, 'TEXT',
      Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\'';
  return [argument0 + operator, Blockly.Dart.ORDER_UNARY_POSTFIX];
};

Blockly.Dart.text_trim.OPERATORS = {
  LEFT: '.replaceFirst(new RegExp(@"^\\s+"), \'\')',
  RIGHT: '.replaceFirst(new RegExp(@"\\s+$"), \'\')',
  BOTH: '.trim()'
};

Blockly.Dart.text_print = function() {
  // Print statement.
  var argument0 = Blockly.Dart.valueToCode(this, 'TEXT',
      Blockly.Dart.ORDER_NONE) || '\'\'';
  return 'print(' + argument0 + ');\n';
};

Blockly.Dart.text_prompt = function() {
  // Prompt function.
  Blockly.Dart.definitions_['import_dart_html'] = '#import(\'dart:html\');';
  var msg = Blockly.Dart.quote_(this.getTitleValue('TEXT'));
  var code = 'window.prompt(' + msg + ', \'\')';
  var toNumber = this.getTitleValue('TYPE') == 'NUMBER';
  if (toNumber) {
    code = 'Math.parseDouble(' + code + ')';
  }
  return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};
<|endoftext|>


<commit_before>module.exports = {

//---------------------------------------------------------------------
// Action Name
//
// This is the name of the action displayed in the editor.
//---------------------------------------------------------------------

name: "Welcome",

//---------------------------------------------------------------------
// Action Section
//
// This is the section the action will fall into.
//---------------------------------------------------------------------

section: "#Mod Information",

//---------------------------------------------------------------------
// Action Subtitle
//
// This function generates the subtitle displayed next to the name.
//---------------------------------------------------------------------

subtitle: function(data) {
return `Put this into a Bot Initalization event for music!`;
},

//---------------------------------------------------------------------
// DBM Mods Manager Variables (Optional but nice to have!)
//
// These are variables that DBM Mods Manager uses to show information
// about the mods for people to see in the list.
//---------------------------------------------------------------------

// Who made the mod (If not set, defaults to "DBM Mods")
author: "DBM Mods",

// The version of the mod (Defaults to 1.0.0)
version: "1.9.4 ~ beta",

// A short description to show on the mod line for this mod.
short_description: "Information about the Mod Collection & Overwrites Bot.js",

// If it depends on any other mods by name, ex: WrexMODS if the mod uses something from WrexMods

//---------------------------------------------------------------------

//---------------------------------------------------------------------
// Action Storage Function
//
// Stores the relevant variable info for the editor.
//---------------------------------------------------------------------

variableStorage: function(data, varType) {},

//---------------------------------------------------------------------
// Action Fields
//
// These are the fields for the action. These fields are customized
// by creating elements with corresponding IDs in the HTML. These
// are also the names of the fields stored in the action's JSON data.
//---------------------------------------------------------------------

fields: ["mods"],

//---------------------------------------------------------------------
// Command HTML
//
// This function returns a string containing the HTML used for
// editting actions.
//
// The "isEvent" parameter will be true if this action is being used
// for an event. Due to their nature, events lack certain information,
// so edit the HTML to reflect this.
//
// The "data" parameter stores constants for select elements to use.
// Each is an array: index 0 for commands, index 1 for events.
// The names are: sendTargets, members, roles, channels,
//                messages, servers, variables
//---------------------------------------------------------------------

html: function(isEvent, data) {
return `

Welcome!

Thank you for using the DBM Mod Collection!

If you want to tell us something, join the Discord Guild below.
And if something doesn't work feel free to create an issue on GitHub
or open #support and describe your problem.

Discord:

Join the Discord Guild to stay updated and be able to suggest things.

https://dbm-network.org/

Your version:

${this.version}

Our Donators:

        <embedleftline></embedleftline>

                Our Supporters

		Sam

		Zaserr

		papa goobs

		Danno3817

		GeT_DuCkT

		Nerd

		squiffy

		Noah

		Adam_V

		DoimptSopy

		Lasse

		Not Alien

		𝕯𝖔𝖒

		Leondre Devries [BAM]

		_iTrqPss

		NetLuis

		Almeida

		Orochimaru

		Max 🌟

		GAMER

		S h i r o ツ

		Quinten

		Rafied

		lucasboss45

		Dominus_Marceau

GitHub:

Visit us on GitHub! The whole mod collection is on GitHub
and everyone is invited to join us developing new mods!

Copy and paste the link to view the site in your browser.

https://github.com/Discord-Bot-Maker-Mods/DBM-Mods

Current List of Mods

Name
Section
Author(s)

`
},

//---------------------------------------------------------------------
// Action Editor Init Code
//
// When the HTML is first applied to the action editor, this code
// is also run. This helps add modifications or setup reactionary
// functions for the DOM elements.
//---------------------------------------------------------------------

init: function() {
const {glob, document} = this;

var path = require("path")

try {

	var mods = document.getElementById("mods");

	require("fs").readdirSync(__dirname).forEach(function(file) {
		if(file.match(/MOD.js/i)) {
			var action = require(path.join(__dirname, file));
			if(action.name && action.action !== null) {

				const tr = document.createElement('tr')
				tr.setAttribute('class', 'table-dark')

				const name = document.createElement('td')
				const headerText = document.createElement("b")
				headerText.innerHTML = action.name
				name.appendChild(headerText)

				name.setAttribute('scope', 'row')
				tr.appendChild(name)

				const section = document.createElement('td')
				section.appendChild(document.createTextNode(action.section))
				tr.appendChild(section)

				const author = document.createElement('td')
				author.appendChild(document.createTextNode(action.author ? action.author : "DBM"))
				tr.appendChild(author)
				mods.appendChild(tr);
			}
		}
	});
} catch (error) {
	// write any init errors to errors.txt in dbm's main directory
	require("fs").appendFile("errors.txt", error.stack ? error.stack : error + "\r\n");
}

var wrexlinks = document.getElementsByClassName("wrexlink")
	for(var x = 0; x < wrexlinks.length; x++) {
	    var wrexlink = wrexlinks[x];
	    var url = wrexlink.getAttribute('data-url');
	    if(url){
		    wrexlink.addEventListener("click", function(e){
		        e.stopImmediatePropagation();
		        console.log("Launching URL: [" + url + "] in your default browser.");
		        require('child_process').execSync('start ' + url);
		    });
	    }
	}

var wrexlinks2 = document.getElementsByClassName("wrexlink2")
	for(var x2 = 0; x2 < wrexlinks2.length; x2++) {
	    var wrexlink2 = wrexlinks2[x2];
	    var url2 = wrexlink2.getAttribute('data-url2');
	    if(url2){
		    wrexlink2.setAttribute("title", url2);
		    wrexlink2.addEventListener("click", function(e2){
		        e2.stopImmediatePropagation();
		        console.log("Launching URL: [" + url2 + "] in your default browser.");
		        require('child_process').execSync('start ' + url2);
		    });
	    }
	}

var wrexlinks3 = document.getElementsByClassName("wrexlink3")
	for(var x3 = 0; x3 < wrexlinks3.length; x3++) {
	    var wrexlink3 = wrexlinks3[x3];
	    var url3 = wrexlink3.getAttribute('data-url3');
	    if(url3){
		    wrexlink3.setAttribute("title", url3);
		    wrexlink3.addEventListener("click", function(e3){
		        e3.stopImmediatePropagation();
		        console.log("Launching URL: [" + url3 + "] in your default browser.");
		        require('child_process').execSync('start ' + url3);
		    });
	    }
	}
},

//---------------------------------------------------------------------
// Action Bot Function
//
// This is the function for the action within the Bot's Action class.
// Keep in mind event calls won't have access to the "msg" parameter,
// so be sure to provide checks for variable existance.
//---------------------------------------------------------------------

action: function(cache) {

console.log('Music function successfully overwritten.');

},

//---------------------------------------------------------------------
// Action Bot Mod
//
// Upon initialization of the bot, this code is run. Using the bot's
// DBM namespace, one can add/modify existing functions if necessary.
// In order to reduce conflictions between mods, be sure to alias
// functions you wish to overwrite.
//---------------------------------------------------------------------

mod: function(DBM) {
DBM.Audio.playingnow = [];

var oldFunc = DBM.Audio.playItem;
DBM.Audio.playItem = function(item, id) {
	oldFunc.apply(this, arguments);
	if(item[0] === "yt") {
		this.playingnow[id] = item;
	}
};
}

}; // End of module
<commit_msg>ignore this<commit_after>module.exports = {

//---------------------------------------------------------------------
// Action Name
//
// This is the name of the action displayed in the editor.
//---------------------------------------------------------------------

name: "Welcome",

//---------------------------------------------------------------------
// Action Section
//
// This is the section the action will fall into.
//---------------------------------------------------------------------

section: "#Mod Information",

//---------------------------------------------------------------------
// Action Subtitle
//
// This function generates the subtitle displayed next to the name.
//---------------------------------------------------------------------

subtitle: function(data) {
return `Put this into a Bot Initalization event for music!`;
},

//---------------------------------------------------------------------
// DBM Mods Manager Variables (Optional but nice to have!)
//
// These are variables that DBM Mods Manager uses to show information
// about the mods for people to see in the list.
//---------------------------------------------------------------------

// Who made the mod (If not set, defaults to "DBM Mods")
author: "DBM Mods",

// The version of the mod (Defaults to 1.0.0)
version: "1.9.4 ~ beta",

// A short description to show on the mod line for this mod.
short_description: "Information about the Mod Collection & Overwrites Bot.js",

// If it depends on any other mods by name, ex: WrexMODS if the mod uses something from WrexMods

//---------------------------------------------------------------------

//---------------------------------------------------------------------
// Action Storage Function
//
// Stores the relevant variable info for the editor.
//---------------------------------------------------------------------

variableStorage: function(data, varType) {},

//---------------------------------------------------------------------
// Action Fields
//
// These are the fields for the action. These fields are customized
// by creating elements with corresponding IDs in the HTML. These
// are also the names of the fields stored in the action's JSON data.
//---------------------------------------------------------------------

fields: ["mods"],

//---------------------------------------------------------------------
// Command HTML
//
// This function returns a string containing the HTML used for
// editting actions.
//
// The "isEvent" parameter will be true if this action is being used
// for an event. Due to their nature, events lack certain information,
// so edit the HTML to reflect this.
//
// The "data" parameter stores constants for select elements to use.
// Each is an array: index 0 for commands, index 1 for events.
// The names are: sendTargets, members, roles, channels,
//                messages, servers, variables
//---------------------------------------------------------------------

html: function(isEvent, data) {
return `

Welcome!

Thank you for using the DBM Mod Collection!

If you want to tell us something, join the Discord Guild below.
And if something doesn't work feel free to create an issue on GitHub
or open #support and describe your problem.

Discord:

Join the Discord Guild to stay updated and be able to suggest things.

https://dbm-network.org/

Your version:

${this.version}

Our Donators:

        <embedleftline></embedleftline>

                Our Supporters

		Sam

		Zaserr

		papa goobs

		Danno3817

		GeT_DuCkT

		Nerd

		squiffy

		Noah

		Adam_V

		DoimptSopy

		Lasse

		Not Alien

		𝕯𝖔𝖒

		Leondre Devries [BAM]

		_iTrqPss

		NetLuis

		Almeida

		Orochimaru

		Max 🌟

		GAMER

		S h i r o ツ

		Quinten

		Rafied

		lucasboss45

		Dominus_Marceau

GitHub:

Visit us on GitHub! The whole mod collection is on GitHub
and everyone is invited to join us developing new mods!

Copy and paste the link to view the site in your browser.

https://github.com/Discord-Bot-Maker-Mods/DBM-Mods

Current List of Mods

Name
Section
Author(s)

`
},

//---------------------------------------------------------------------
// Action Editor Init Code
//
// When the HTML is first applied to the action editor, this code
// is also run. This helps add modifications or setup reactionary
// functions for the DOM elements.
//---------------------------------------------------------------------

init: function() {
const {glob, document} = this;

var path = require("path")

try {

	var mods = document.getElementById("mods");

	require("fs").readdirSync(__dirname).forEach(function(file) {
		if(file.match(/MOD.js/i)) {
			var action = require(path.join(__dirname, file));
			if(action.name && action.action !== null) {

				const tr = document.createElement('tr')
				tr.setAttribute('class', 'table-dark')

				const name = document.createElement('td')
				const headerText = document.createElement("b")
				headerText.innerHTML = action.name
				name.appendChild(headerText)

				name.setAttribute('scope', 'row')
				tr.appendChild(name)

				const section = document.createElement('td')
				section.appendChild(document.createTextNode(action.section))
				tr.appendChild(section)

				const author = document.createElement('td')
				author.appendChild(document.createTextNode(action.author ? action.author : "DBM"))
				tr.appendChild(author)
				mods.appendChild(tr);
			}
		}
	});
} catch (error) {
	// write any init errors to errors.txt in dbm's main directory
	require("fs").appendFile("errors.txt", error.stack ? error.stack : error + "\r\n");
}

var wrexlinks = document.getElementsByClassName("wrexlink")
	for(var x = 0; x < wrexlinks.length; x++) {
	    var wrexlink = wrexlinks[x];
	    var url = wrexlink.getAttribute('data-url');
	    if(url){
		    wrexlink.addEventListener("click", function(e){
		        e.stopImmediatePropagation();
		        console.log("Launching URL: [" + url + "] in your default browser.");
		        require('child_process').execSync('start ' + url);
		    });
	    }
	}

var wrexlinks2 = document.getElementsByClassName("wrexlink2")
	for(var x2 = 0; x2 < wrexlinks2.length; x2++) {
	    var wrexlink2 = wrexlinks2[x2];
	    var url2 = wrexlink2.getAttribute('data-url2');
	    if(url2){
		    wrexlink2.setAttribute("title", url2);
		    wrexlink2.addEventListener("click", function(e2){
		        e2.stopImmediatePropagation();
		        console.log("Launching URL: [" + url2 + "] in your default browser.");
		        require('child_process').execSync('start ' + url2);
		    });
	    }
	}

var wrexlinks3 = document.getElementsByClassName("wrexlink3")
	for(var x3 = 0; x3 < wrexlinks3.length; x3++) {
	    var wrexlink3 = wrexlinks3[x3];
	    var url3 = wrexlink3.getAttribute('data-url3');
	    if(url3){
		    wrexlink3.setAttribute("title", url3);
		    wrexlink3.addEventListener("click", function(e3){
		        e3.stopImmediatePropagation();
		        console.log("Launching URL: [" + url3 + "] in your default browser.");
		        require('child_process').execSync('start ' + url3);
		    });
	    }
	}
},

//---------------------------------------------------------------------
// Action Bot Function
//
// This is the function for the action within the Bot's Action class.
// Keep in mind event calls won't have access to the "msg" parameter,
// so be sure to provide checks for variable existance.
//---------------------------------------------------------------------

action: function(cache) {

console.log('Music function successfully overwritten.');

},

//---------------------------------------------------------------------
// Action Bot Mod
//
// Upon initialization of the bot, this code is run. Using the bot's
// DBM namespace, one can add/modify existing functions if necessary.
// In order to reduce conflictions between mods, be sure to alias
// functions you wish to overwrite.
//---------------------------------------------------------------------

mod: function(DBM) {
DBM.Audio.playingnow = [];

var oldFunc = DBM.Audio.playItem;
DBM.Audio.playItem = function(item, id) {
	oldFunc.apply(this, arguments);
	if(item[0] === "yt") {
		this.playingnow[id] = item;
	}
};
}

}; // End of module
<|endoftext|>


<commit_before>// @flow

import type { ActivityList } from './activity-list.js'

const AstNode = require('../parsers/ast-node.js')
const AstNodeList = require('../parsers/ast-node-list.js')
const kebabCase = require('just-kebab-case')
const UnprintedUserError = require('../errors/unprinted-user-error.js')

// Returns all activities contained in the given collection of AstNodeLists
module.exports = function (ASTs: AstNodeList[], prefix: string): ActivityList {
  var result: ActivityList = []
  for (let AST of ASTs) {
    result = result.concat(extractActivities(AST, prefix))
  }
  return result
}

// Returns the activities contained in the given AstNodeList
function extractActivities (AST: AstNodeList, prefix: string): ActivityList {
  const result: ActivityList = []
  var activeNode: ?AstNode = null
  for (let node of AST) {
    if (isActiveBlockStartTag(node, prefix)) {
      ensureNoNestedActiveNode(node, activeNode)
      activeNode = node
      result.push({
        type: kebabCase(node.attributes[prefix]),
        file: node.file,
        line: node.line,
        nodes: AST.getNodesFor(node)
      })
    }
    if (isActiveBlockEndTag(node, activeNode, prefix)) {
      activeNode = null
    }
  }
  return result
}

function ensureNoNestedActiveNode (node: AstNode, activeNode: ?AstNode) {
  if (activeNode) {
    throw new UnprintedUserError(
      `${node.file}: block ${node.type || ''} (line ${
        node.line
      }) is nested in block ${activeNode.type} (line ${activeNode.line})`,
      node.file,
      node.line
    )
  }
}

function isActiveBlockStartTag (node: AstNode, classPrefix: string): boolean {
  return !!node.attributes[classPrefix] && node.type.endsWith('_open')
}

function isActiveBlockEndTag (
  node: AstNode,
  activeNode: ?AstNode,
  prefix: string
): boolean {
  if (!activeNode) return false
  return node.attributes[prefix] === activeNode.attributes[prefix]
}
<commit_msg>Allow stand-alone tags as active tags<commit_after>// @flow

import type { ActivityList } from './activity-list.js'

const AstNode = require('../parsers/ast-node.js')
const AstNodeList = require('../parsers/ast-node-list.js')
const kebabCase = require('just-kebab-case')
const UnprintedUserError = require('../errors/unprinted-user-error.js')

// Returns all activities contained in the given collection of AstNodeLists
module.exports = function (ASTs: AstNodeList[], prefix: string): ActivityList {
  var result: ActivityList = []
  for (let AST of ASTs) {
    result = result.concat(extractActivities(AST, prefix))
  }
  return result
}

// Returns the activities contained in the given AstNodeList
function extractActivities (AST: AstNodeList, prefix: string): ActivityList {
  const result: ActivityList = []
  var activeNode: ?AstNode = null
  for (let node of AST) {
    if (isActiveBlockTag(node, prefix)) {
      ensureNoNestedActiveNode(node, activeNode)
      activeNode = node
      result.push({
        type: kebabCase(node.attributes[prefix]),
        file: node.file,
        line: node.line,
        nodes: AST.getNodesFor(node)
      })
    }
    if (isActiveBlockEndTag(node, activeNode, prefix)) {
      activeNode = null
    }
  }
  return result
}

function ensureNoNestedActiveNode (node: AstNode, activeNode: ?AstNode) {
  if (activeNode) {
    throw new UnprintedUserError(
      `${node.file}: block ${node.type || ''} (line ${
        node.line
      }) is nested in block ${activeNode.type} (line ${activeNode.line})`,
      node.file,
      node.line
    )
  }
}

function isActiveBlockTag (node: AstNode, classPrefix: string): boolean {
  return !!node.attributes[classPrefix] && !node.type.endsWith('_close')
}

function isActiveBlockEndTag (
  node: AstNode,
  activeNode: ?AstNode,
  prefix: string
): boolean {
  if (!activeNode) return false
  return node.attributes[prefix] === activeNode.attributes[prefix]
}
<|endoftext|>


<commit_before>var skyBox = require('./sky_box'),
    star = require('./star'),
    TWEEN = require('tween.js'),
    global = require('../../lib/util').global(),
    raf = require('raf-component'),
    THREE = require('three');

module.exports = function scene (skyboxCubeTexture, starTexture1, starTexture2, starTexture3) {
  var distance = 2000,
      camera,
      world,
      renderer;

  camera = new THREE.PerspectiveCamera(45, global.innerWidth / global.innerHeight, 0.1, 100000000);
  camera.up = new THREE.Vector3(0, 0, 1);
  camera.useQuaternion = true;
  camera.position.z = 3000;
  world = new THREE.Scene();

  renderer = new THREE.WebGLRenderer({ antialias: true });

  skyBox(world, skyboxCubeTexture);
  star(world, 6000, 6000, -6000, starTexture1, starTexture2, starTexture3);

  return {
    setSize: setSize,
    render: render,
    domCanvas: renderer.domElement,
    scene: world,
    camera: camera
  };

  function setSize (width, height) {
    camera.aspect = width / height;
    camera.updateProjectionMatrix();
    renderer.setSize(width, height);
  }

  function render () {
    raf(render);
    TWEEN.update();
    renderer.render(world, camera);
  }
};
<commit_msg>Start the camera further from the first planet<commit_after>var skyBox = require('./sky_box'),
    star = require('./star'),
    TWEEN = require('tween.js'),
    global = require('../../lib/util').global(),
    raf = require('raf-component'),
    THREE = require('three');

module.exports = function scene (skyboxCubeTexture, starTexture1, starTexture2, starTexture3) {
  var distance = 2000,
      camera,
      world,
      renderer;

  camera = new THREE.PerspectiveCamera(45, global.innerWidth / global.innerHeight, 0.1, 100000000);
  camera.up = new THREE.Vector3(0, 0, 1);
  camera.useQuaternion = true;
  camera.position.z = 3000;
  camera.position.x = 8000;
  world = new THREE.Scene();

  renderer = new THREE.WebGLRenderer({ antialias: true });

  skyBox(world, skyboxCubeTexture);
  star(world, 6000, 6000, -6000, starTexture1, starTexture2, starTexture3);

  return {
    setSize: setSize,
    render: render,
    domCanvas: renderer.domElement,
    scene: world,
    camera: camera
  };

  function setSize (width, height) {
    camera.aspect = width / height;
    camera.updateProjectionMatrix();
    renderer.setSize(width, height);
  }

  function render () {
    raf(render);
    TWEEN.update();
    renderer.render(world, camera);
  }
};
<|endoftext|>


<commit_before>import Ember from 'ember';
import DS from 'ember-data';

import SnapshotTransform from '../utils/snapshot-transform';
import ODataQueryAdapter from '../query/odata-adapter';
import { capitalize, camelize } from '../utils/string-functions';

const { getOwner } = Ember;

/**
 * The OData adapter class.
 * Uses Flexberry Query as a language for requesting server.
 *
 * @module ember-flexberry-data
 * @namespace Adapter
 * @class OData
 * @extends DS.RESTAdapter
 * @public
 */
export default DS.RESTAdapter.extend({
  headers: {
    Prefer: 'return=representation'
  },

  idType: 'number',

  /**
    Timeout for AJAX-requests.

    @property timeout
    @type Number
    @default 0
  */
  timeout: 0,

  /**
    Overloaded method from `RESTAdapter` (Ember Data).
    Called by the sore in order to fetch data from the server.

    @method query
    @param {DS.Store} store
    @param {DS.Model} type
    @param {Query} query Flexberry Query object.
    @return {Promise}
  */
  query(store, type, query) {
    let url = this._buildURL(query.modelName);
    let builder = new ODataQueryAdapter(url, store);
    let data = builder.getODataQuery(query);
    let timeout = this.get('timeout');

    if (this.sortQueryParams) {
      data = this.sortQueryParams(data);
    }

    Ember.debug(`Flexberry ODataAdapter::query '${type}'`, data);

    //f TODO: think about moving request execution into query adapter
    return this.ajax(url, 'GET', { data: data, timeout: timeout, dataType: query.dataType || 'json' });
  },

  /**
    Overloaded method from `RESTAdapter` (Ember Data).
    Customizes ajax options for the requests.

    @method ajaxOptions
    @param {String} url
    @param {DS.Model} type
    @param {Object} options
    @return {Object}
  */
  ajaxOptions: function ajaxOptions(url, type, options) {
    let dataType = options.dataType;
    let hash = this._super(...arguments);
    if (dataType === 'blob') {
      hash.dataType = dataType;
    }

    return hash;
  },

  /**
    Takes an ajax response, and returns the json payload or an error.

    @method handleResponse
    @param {Number} status
    @param {Object} headers
    @param {Object} payload
  */
  handleResponse(status, headers, payload) {
    if (!this.isSuccess(status, headers, payload) && typeof payload === 'object' && payload.error) {
      return new DS.AdapterError(payload.error.details, payload.error.message);
    }

    return this._super(...arguments);
  },

  /**
   * Overloaded method from `RESTAdapter` (Ember Data).
   * Called by the sore in order to fetch single record from the server.
   *
   * @method queryRecord
   * @param {DS.Store} store
   * @param {DS.Model} type
   * @param {Query} query
   * @return {Promise} promise
   */
  /* jshint unused:vars */
  queryRecord(store, type, query) {
    Ember.debug(`Flexberry ODataAdapter::queryRecord '${type}'`, query);

    // TODO: query support for direct calls
    return this._super.apply(this, arguments);
  },
  /* jshint unused:true */

  /**
   * Overloaded method from `RESTAdapter` (Ember Data).
   * Called by the sore in order to fetch single record by ID from the server.
   *
   * @method findRecord
   * @param {DS.Store} store
   * @param {DS.Model} type
   * @param {String} id
   * @param {DS.Snapshot} snapshot
   * @return {Promise} promise
  */
  /* jshint unused:vars */
  findRecord(store, type, id, snapshot) {
    Ember.debug(`Flexberry ODataAdapter::findRecord '${type}(${id})'`);

    // TODO: query support for direct calls
    return this._super.apply(this, arguments);
  },
  /* jshint unused:true */

  /**
   * Overloaded method from `RESTAdapter` (Ember Data).
   * Called by the sore in order to fetch all records from the server.
   *
   * @method findAll
   * @param {DS.Store} store
   * @param {DS.Model} type
   * @param {String} sinceToken
   * @param {DS.SnapshotRecordArray} snapshotRecordArray
   * @return {Promise} promise
   */
  /* jshint unused:vars */
  findAll(store, type, sinceToken, snapshotRecordArray) {
    Ember.debug(`Flexberry ODataAdapter::findAll '${type}'`);

    // TODO: query support for direct calls
    return this._super.apply(this, arguments);
  },
  /* jshint unused:true */

  /**
   * Overloaded method from `build-url-mixin` (Ember Data), that determines the pathname for a given type.
   * Additionally capitalizes the type name (requirement of Flexberry OData Server).
   *
   * @method pathForType
   * @param {String} modelName
   * @return {String} The path for a given type.
   */
  pathForType(modelName) {
    var camelized = camelize(modelName);
    var capitalized = capitalize(camelized);
    return Ember.String.pluralize(capitalized);
  },

  /**
   * A method to make ajax requests.
   *
   * @method makeRequest
   * @param {Object} params
   * @public
   */
  makeRequest(params) {
    Ember.aserrt('You should specify both method and url', params.method || params.url);
    return Ember.$.ajax(params);
  },

  /**
   * A method to call functions using ajax requests.
   *
   * @method callFunction
   * @param {string} url
   * @param {Object} functionName
   * @param {Object} params
   * @param {Function} successCallback
   * @param {Function} failCallback
   * @param {Function} alwaysCallback
   * @return {Promise}
   * @public
   */
  callFunction(url, functionName, params, successCallback, failCallback, alwaysCallback) {
    let config = getOwner(this)._lookupFactory('config:environment');
    if (Ember.isNone(url)) {
      url = `${config.baseURL}`;
    }

    let resultUrl = `${url}/${functionName}(`;
    let counter = 0;
    for (var key in params) {
      counter++;
    }

    let i = 0;
    for (key in params) {
      //TODO: Check types and ''
      if (typeof params[key] === 'number') {
        resultUrl = resultUrl + `${key}=${params[key]}`;
      } else {
        resultUrl = resultUrl + `${key}='${params[key]}'`;
      }

      if (i < counter) {
        resultUrl += ', ';
      } else {
        resultUrl += ')';
      }

      i++;
    }

    if (resultUrl[resultUrl.length - 1] !== ')') {
      resultUrl += ')';
    }

    return this._callAjax({ url: resultUrl, method: 'GET' }, successCallback, failCallback, alwaysCallback);

  },

  /**
   * A method to call actions using ajax requests.
   *
   * @method callFunction
   * @param {String} url
   * @param {String} actionName
   * @param {Object} data
   * @param {Function} successCallback
   * @param {Function} failCallback
   * @param {Function} alwaysCallback
   * @return {Promise}
   * @public
   */
  callAction(url, actionName, data, successCallback, failCallback, alwaysCallback) {
    let config = getOwner(this)._lookupFactory('config:environment');
    if (Ember.isNone(url)) {
      url = `${config.baseURL}`;
    }

    data = JSON.stringify(data);
    url =  `${url}/${actionName}`;

    return this._callAjax({ data: data, url: url, method: 'POST' }, successCallback, failCallback, alwaysCallback);
  },

  /**
   * A method to make ajax requests.
   *
   * @method _callAjax
   * @param {Object} params
   * @param {Function} successCallback
   * @param {Function} failCallback
   * @param {Function} alwaysCallback
   * @return {Promise}
   * @private
   */
  _callAjax(params, successCallback, failCallback, alwaysCallback) {
    Ember.assert('Params must be Object!', typeof params === 'object');
    Ember.assert('params.method or params.url is not defined.', (Ember.isNone(params.method) && Ember.isNone(params.url)));

    return Ember.RVSP.Promise(function(resolve, reject) {
      Ember.$.ajax(params).done((msg) => {
        if (!Ember.isNone(successCallback)) {
          if (typeof successCallback.then === 'function') {
            if (!Ember.isNone(alwaysCallback)) {
              if (typeof alwaysCallback.then === 'function') {
                successCallback(msg).then(() => {alwaysCallback(msg).then(resolve(msg));});
              } else {
                successCallback(msg).then(alwaysCallback(msg)).then(resolve(msg));
              }
            } else {
              successCallback(msg).then(resolve(msg));
            }
          } else {
            successCallback(msg);
            if (!Ember.isNone(alwaysCallback)) {
              if (typeof alwaysCallback.then === 'function') {
                alwaysCallback(msg).then(resolve(msg));
              } else {
                alwaysCallback(msg);
                resolve(msg);
              }
            } else {
              resolve(msg);
            }
          }
        } else {
          if (!Ember.isNone(alwaysCallback)) {
            if (typeof alwaysCallback.then === 'function') {
              alwaysCallback(msg).then(resolve(msg));
            } else {
              alwaysCallback(msg);
              resolve(msg);
            }
          } else {
            resolve(msg);
          }
        }
      }).fail((msg)=> {
        if (!Ember.isNone(failCallback)) {
          if (typeof failCallback.then === 'function') {
            if (!Ember.isNone(alwaysCallback)) {
              if (typeof alwaysCallback.then === 'function') {
                failCallback(msg).then(() => {alwaysCallback(msg).then(reject(msg));});
              } else {
                failCallback(msg).then(alwaysCallback(msg)).then(reject(msg));
              }

            } else {
              failCallback(msg).then(reject(msg));
            }

          } else {
            failCallback(msg);
            if (!Ember.isNone(alwaysCallback)) {
              if (typeof alwaysCallback === 'function') {
                alwaysCallback(msg).then(reject(msg));
              } else {
                alwaysCallback(msg);
                reject(msg);
              }
            } else {
              reject(msg);
            }
          }
        } else {
          if (!Ember.isNone(alwaysCallback)) {
            if (typeof alwaysCallback.then === 'function') {
              alwaysCallback(msg).then(reject(msg));
            } else {
              alwaysCallback(msg);
              reject(msg);
            }
          } else {
            reject(msg);
          }
        }
      });
    });
  },

  /**
   * Overloaded method from `build-url-mixin` (Ember Data), taht builds URL to OData feed.
   * Appends id as `(id)` (OData specification) instead of `/id`.
   *
   * @method _buildURL
   * @param {String} modelName
   * @param {String} id
   * @return {String}
   * @private
   */
  _buildURL(modelName, id) {
    var url = [];
    var host = Ember.get(this, 'host');
    var prefix = this.urlPrefix();
    var path;

    if (modelName) {
      path = this.pathForType(modelName);
      if (path) {
        url.push(path);
      }
    }

    if (prefix) {
      url.unshift(prefix);
    }

    url = url.join('/');
    if (!host && url && url.charAt(0) !== '/') {
      url = '/' + url;
    }

    if (id != null) {
      // Append id as `(id)` (OData specification) instead of `/id`.
      url = this._appendIdToURL(id, url);
    }

    return url;
  },

  /**
   * Appends id to URL according to the OData specification.
   *
   * @method _appendIdToURL
   * @param {String} id
   * @param {String} url
   * @private
   */
  _appendIdToURL(id, url) {
    let encId = encodeURIComponent(id);
    let idType = Ember.get(this, 'idType');
    if (idType !== 'number') {
      encId = `'${encId}'`;
    }

    url += '(' + encId + ')';
    return url;
  },

  createRecord(store, type, snapshot) {
    return this._sendRecord(store, type, snapshot, 'createRecord');
  },

  updateRecord(store, type, snapshot) {
    return this._sendRecord(store, type, snapshot, 'updateRecord');
  },

  deleteRecord(store, type, snapshot) {
    return this._sendRecord(store, type, snapshot, 'deleteRecord');
  },

  /**
   * Makes HTTP request for creating, updating or deleting the record.
   *
   * @method _sendRecord
   * @private
   */
  _sendRecord(store, type, snapshot, requestType) {
    // TODO: maybe move it into serializer (serialize or serializeIntoHash)?
    let skipUnchangedAttrs = true;
    SnapshotTransform.transformForSerialize(snapshot, skipUnchangedAttrs);

    // NOTE: for newly created records id is not defined.
    let url = this.buildURL(type.modelName, snapshot.id, snapshot, requestType);

    let httpMethod;
    switch (requestType) {
      case 'createRecord':
        httpMethod = 'POST';
        break;

      case 'updateRecord':
        httpMethod = skipUnchangedAttrs ? 'PATCH' : 'PUT';
        break;

      case 'deleteRecord':
        httpMethod = 'DELETE';
        break;

      default:
        throw new Error(`Unknown requestType: ${requestType}`);
    }

    let data;

    // Don't need to send any data for deleting.
    if (requestType !== 'deleteRecord') {
      let serializer = store.serializerFor(type.modelName);
      data = {};
      serializer.serializeIntoHash(data, type, snapshot);
    }

    return this.ajax(url, httpMethod, { data: data }).then(function(response) {
      return response;
    });
  }
});
<commit_msg>Fix mistakes, now it works<commit_after>import Ember from 'ember';
import DS from 'ember-data';

import SnapshotTransform from '../utils/snapshot-transform';
import ODataQueryAdapter from '../query/odata-adapter';
import { capitalize, camelize } from '../utils/string-functions';

const { getOwner } = Ember;

/**
 * The OData adapter class.
 * Uses Flexberry Query as a language for requesting server.
 *
 * @module ember-flexberry-data
 * @namespace Adapter
 * @class OData
 * @extends DS.RESTAdapter
 * @public
 */
export default DS.RESTAdapter.extend({
  headers: {
    Prefer: 'return=representation'
  },

  idType: 'number',

  /**
    Timeout for AJAX-requests.

    @property timeout
    @type Number
    @default 0
  */
  timeout: 0,

  /**
    Overloaded method from `RESTAdapter` (Ember Data).
    Called by the sore in order to fetch data from the server.

    @method query
    @param {DS.Store} store
    @param {DS.Model} type
    @param {Query} query Flexberry Query object.
    @return {Promise}
  */
  query(store, type, query) {
    let url = this._buildURL(query.modelName);
    let builder = new ODataQueryAdapter(url, store);
    let data = builder.getODataQuery(query);
    let timeout = this.get('timeout');

    if (this.sortQueryParams) {
      data = this.sortQueryParams(data);
    }

    Ember.debug(`Flexberry ODataAdapter::query '${type}'`, data);

    //f TODO: think about moving request execution into query adapter
    return this.ajax(url, 'GET', { data: data, timeout: timeout, dataType: query.dataType || 'json' });
  },

  /**
    Overloaded method from `RESTAdapter` (Ember Data).
    Customizes ajax options for the requests.

    @method ajaxOptions
    @param {String} url
    @param {DS.Model} type
    @param {Object} options
    @return {Object}
  */
  ajaxOptions: function ajaxOptions(url, type, options) {
    let dataType = options.dataType;
    let hash = this._super(...arguments);
    if (dataType === 'blob') {
      hash.dataType = dataType;
    }

    return hash;
  },

  /**
    Takes an ajax response, and returns the json payload or an error.

    @method handleResponse
    @param {Number} status
    @param {Object} headers
    @param {Object} payload
  */
  handleResponse(status, headers, payload) {
    if (!this.isSuccess(status, headers, payload) && typeof payload === 'object' && payload.error) {
      return new DS.AdapterError(payload.error.details, payload.error.message);
    }

    return this._super(...arguments);
  },

  /**
   * Overloaded method from `RESTAdapter` (Ember Data).
   * Called by the sore in order to fetch single record from the server.
   *
   * @method queryRecord
   * @param {DS.Store} store
   * @param {DS.Model} type
   * @param {Query} query
   * @return {Promise} promise
   */
  /* jshint unused:vars */
  queryRecord(store, type, query) {
    Ember.debug(`Flexberry ODataAdapter::queryRecord '${type}'`, query);

    // TODO: query support for direct calls
    return this._super.apply(this, arguments);
  },
  /* jshint unused:true */

  /**
   * Overloaded method from `RESTAdapter` (Ember Data).
   * Called by the sore in order to fetch single record by ID from the server.
   *
   * @method findRecord
   * @param {DS.Store} store
   * @param {DS.Model} type
   * @param {String} id
   * @param {DS.Snapshot} snapshot
   * @return {Promise} promise
  */
  /* jshint unused:vars */
  findRecord(store, type, id, snapshot) {
    Ember.debug(`Flexberry ODataAdapter::findRecord '${type}(${id})'`);

    // TODO: query support for direct calls
    return this._super.apply(this, arguments);
  },
  /* jshint unused:true */

  /**
   * Overloaded method from `RESTAdapter` (Ember Data).
   * Called by the sore in order to fetch all records from the server.
   *
   * @method findAll
   * @param {DS.Store} store
   * @param {DS.Model} type
   * @param {String} sinceToken
   * @param {DS.SnapshotRecordArray} snapshotRecordArray
   * @return {Promise} promise
   */
  /* jshint unused:vars */
  findAll(store, type, sinceToken, snapshotRecordArray) {
    Ember.debug(`Flexberry ODataAdapter::findAll '${type}'`);

    // TODO: query support for direct calls
    return this._super.apply(this, arguments);
  },
  /* jshint unused:true */

  /**
   * Overloaded method from `build-url-mixin` (Ember Data), that determines the pathname for a given type.
   * Additionally capitalizes the type name (requirement of Flexberry OData Server).
   *
   * @method pathForType
   * @param {String} modelName
   * @return {String} The path for a given type.
   */
  pathForType(modelName) {
    var camelized = camelize(modelName);
    var capitalized = capitalize(camelized);
    return Ember.String.pluralize(capitalized);
  },

  /**
   * A method to make ajax requests.
   *
   * @method makeRequest
   * @param {Object} params
   * @public
   */
  makeRequest(params) {
    Ember.aserrt('You should specify both method and url', params.method || params.url);
    return Ember.$.ajax(params);
  },

  /**
   * A method to call functions using ajax requests.
   *
   * @method callFunction
   * @param {string} url
   * @param {Object} functionName
   * @param {Object} params
   * @param {Function} successCallback
   * @param {Function} failCallback
   * @param {Function} alwaysCallback
   * @return {Promise}
   * @public
   */
  callFunction(url, functionName, params, successCallback, failCallback, alwaysCallback) {
    let config = getOwner(this)._lookupFactory('config:environment');
    if (Ember.isNone(url)) {
      url = `${config.APP.backendUrls.api}`;
    }

    let resultUrl = `${url}/${functionName}(`;
    let counter = 0;
    for (var key in params) {
      counter++;
    }

    let i = 0;
    for (key in params) {
      //TODO: Check types and ''
      if (typeof params[key] === 'number') {
        resultUrl = resultUrl + `${key}=${params[key]}`;
      } else {
        resultUrl = resultUrl + `${key}='${params[key]}'`;
      }

      i++;
      if (i < counter) {
        resultUrl += ',';
      } else {
        resultUrl += ')';
      }
    }

    if (resultUrl[resultUrl.length - 1] !== ')') {
      resultUrl += ')';
    }

    return this._callAjax({ url: resultUrl, method: 'GET' }, successCallback, failCallback, alwaysCallback);

  },

  /**
   * A method to call actions using ajax requests.
   *
   * @method callFunction
   * @param {String} url
   * @param {String} actionName
   * @param {Object} data
   * @param {Function} successCallback
   * @param {Function} failCallback
   * @param {Function} alwaysCallback
   * @return {Promise}
   * @public
   */
  callAction(url, actionName, data, successCallback, failCallback, alwaysCallback) {
    let config = getOwner(this)._lookupFactory('config:environment');
    if (Ember.isNone(url)) {
      url = `${config.APP.backendUrls.api}`;
    }

    data = JSON.stringify(data);
    url =  `${url}/${actionName}`;

    return this._callAjax({ data: data, url: url, method: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'json' }, successCallback, failCallback, alwaysCallback);
  },

  /**
   * A method to make ajax requests.
   *
   * @method _callAjax
   * @param {Object} params
   * @param {Function} successCallback
   * @param {Function} failCallback
   * @param {Function} alwaysCallback
   * @return {Promise}
   * @private
   */
  _callAjax(params, successCallback, failCallback, alwaysCallback) {
    Ember.assert('Params must be Object!', typeof params === 'object');
    Ember.assert('params.method or params.url is not defined.', !(Ember.isNone(params.method) || Ember.isNone(params.url)));

    return new Ember.RSVP.Promise(function(resolve, reject) {
      Ember.$.ajax(params).done((msg) => {
        if (!Ember.isNone(successCallback)) {
          if (typeof successCallback.then === 'function') {
            if (!Ember.isNone(alwaysCallback)) {
              if (typeof alwaysCallback.then === 'function') {
                successCallback(msg).then(() => {alwaysCallback(msg).then(resolve(msg));});
              } else {
                successCallback(msg).then(alwaysCallback(msg)).then(resolve(msg));
              }
            } else {
              successCallback(msg).then(resolve(msg));
            }
          } else {
            successCallback(msg);
            if (!Ember.isNone(alwaysCallback)) {
              if (typeof alwaysCallback.then === 'function') {
                alwaysCallback(msg).then(resolve(msg));
              } else {
                alwaysCallback(msg);
                resolve(msg);
              }
            } else {
              resolve(msg);
            }
          }
        } else {
          if (!Ember.isNone(alwaysCallback)) {
            if (typeof alwaysCallback.then === 'function') {
              alwaysCallback(msg).then(resolve(msg));
            } else {
              alwaysCallback(msg);
              resolve(msg);
            }
          } else {
            resolve(msg);
          }
        }
      }).fail((msg)=> {
        if (!Ember.isNone(failCallback)) {
          if (typeof failCallback.then === 'function') {
            if (!Ember.isNone(alwaysCallback)) {
              if (typeof alwaysCallback.then === 'function') {
                failCallback(msg).then(() => {alwaysCallback(msg).then(reject(msg));});
              } else {
                failCallback(msg).then(alwaysCallback(msg)).then(reject(msg));
              }

            } else {
              failCallback(msg).then(reject(msg));
            }

          } else {
            failCallback(msg);
            if (!Ember.isNone(alwaysCallback)) {
              if (typeof alwaysCallback === 'function') {
                alwaysCallback(msg).then(reject(msg));
              } else {
                alwaysCallback(msg);
                reject(msg);
              }
            } else {
              reject(msg);
            }
          }
        } else {
          if (!Ember.isNone(alwaysCallback)) {
            if (typeof alwaysCallback.then === 'function') {
              alwaysCallback(msg).then(reject(msg));
            } else {
              alwaysCallback(msg);
              reject(msg);
            }
          } else {
            reject(msg);
          }
        }
      });
    });
  },

  /**
   * Overloaded method from `build-url-mixin` (Ember Data), taht builds URL to OData feed.
   * Appends id as `(id)` (OData specification) instead of `/id`.
   *
   * @method _buildURL
   * @param {String} modelName
   * @param {String} id
   * @return {String}
   * @private
   */
  _buildURL(modelName, id) {
    var url = [];
    var host = Ember.get(this, 'host');
    var prefix = this.urlPrefix();
    var path;

    if (modelName) {
      path = this.pathForType(modelName);
      if (path) {
        url.push(path);
      }
    }

    if (prefix) {
      url.unshift(prefix);
    }

    url = url.join('/');
    if (!host && url && url.charAt(0) !== '/') {
      url = '/' + url;
    }

    if (id != null) {
      // Append id as `(id)` (OData specification) instead of `/id`.
      url = this._appendIdToURL(id, url);
    }

    return url;
  },

  /**
   * Appends id to URL according to the OData specification.
   *
   * @method _appendIdToURL
   * @param {String} id
   * @param {String} url
   * @private
   */
  _appendIdToURL(id, url) {
    let encId = encodeURIComponent(id);
    let idType = Ember.get(this, 'idType');
    if (idType !== 'number') {
      encId = `'${encId}'`;
    }

    url += '(' + encId + ')';
    return url;
  },

  createRecord(store, type, snapshot) {
    return this._sendRecord(store, type, snapshot, 'createRecord');
  },

  updateRecord(store, type, snapshot) {
    return this._sendRecord(store, type, snapshot, 'updateRecord');
  },

  deleteRecord(store, type, snapshot) {
    return this._sendRecord(store, type, snapshot, 'deleteRecord');
  },

  /**
   * Makes HTTP request for creating, updating or deleting the record.
   *
   * @method _sendRecord
   * @private
   */
  _sendRecord(store, type, snapshot, requestType) {
    // TODO: maybe move it into serializer (serialize or serializeIntoHash)?
    let skipUnchangedAttrs = true;
    SnapshotTransform.transformForSerialize(snapshot, skipUnchangedAttrs);

    // NOTE: for newly created records id is not defined.
    let url = this.buildURL(type.modelName, snapshot.id, snapshot, requestType);

    let httpMethod;
    switch (requestType) {
      case 'createRecord':
        httpMethod = 'POST';
        break;

      case 'updateRecord':
        httpMethod = skipUnchangedAttrs ? 'PATCH' : 'PUT';
        break;

      case 'deleteRecord':
        httpMethod = 'DELETE';
        break;

      default:
        throw new Error(`Unknown requestType: ${requestType}`);
    }

    let data;

    // Don't need to send any data for deleting.
    if (requestType !== 'deleteRecord') {
      let serializer = store.serializerFor(type.modelName);
      data = {};
      serializer.serializeIntoHash(data, type, snapshot);
    }

    return this.ajax(url, httpMethod, { data: data }).then(function(response) {
      return response;
    });
  }
});
<|endoftext|>