<commit_before>import path             from 'path';
import fs               from 'fs';
import Metalsmith       from 'metalsmith';
import deepAssign       from 'deep-assign';
import collections      from 'metalsmith-collections';
import metadata         from 'metalsmith-metadata';
import markdown         from 'metalsmith-markdown';
import layouts          from 'metalsmith-layouts';
import inPlace          from 'metalsmith-in-place';
import permalinks       from 'metalsmith-permalinks';
import pagination       from 'metalsmith-pagination';
import excerpts         from 'metalsmith-excerpts';
import sass             from 'metalsmith-sass';
import moment           from 'moment';
import define           from 'metalsmith-define';
import jekyllDates      from 'metalsmith-jekyll-dates';
import autoprefixer     from 'metalsmith-autoprefixer';
import webpack          from 'metalsmith-webpack';
import ignore           from 'metalsmith-ignore';
import metallic         from 'metalsmith-metallic';
import tags             from 'metalsmith-tags';
import snippet          from 'metalsmith-snippet';
import blc              from 'metalsmith-broken-link-checker';
import date             from 'metalsmith-build-date';
// prod
import htmlMinifier     from 'metalsmith-html-minifier';
import fingerprint      from 'metalsmith-fingerprint';
import imagemin         from 'metalsmith-imagemin';
import sitemap          from 'metalsmith-sitemap';
import firebase         from 'metalsmith-firebase';
import rss              from 'metalsmith-rss';
import drafts           from 'metalsmith-drafts';

export default function (config = {}, callback) {

  const DEFAULT_OPTIONS = {
    metadata: {
      title: 'Metalpress',
      description: 'Create a blog with Metalpress.',
      url: 'https://metalpress.io',
      production: false
    },
    filedata: {},
    sitemap: false,
    rss: false,
    ignore: [
      'data/**',
      '_data/**',
      '_drafts/*.md',
      'templates/**',
      'lib/**',
      'lib/**/.gitignore',
      'lib/**/.bower.json',
      'lib/**/.jshintrc',
      'assets/js/**/!(.min).js'
    ],
    markdown: {
      gfm: true,
      tables: true
    },
    permalinks: {
      relative: false,
      pattern: ':title'
    },
    layouts: {
      engine: 'liquid',
      directory: 'templates/_layouts',
      includeDir: 'templates/_includes'
    },
    inPlace: {
      engine: 'liquid',
      pattern: '**/*.liquid',
      includeDir: 'templates/_includes'
    },
    fingerprint: {
      pattern: 'assets/css/main.css'
    },
    tags: {
      // yaml key for tag list in you pages
      handle: 'tags',
      // path for result pages
      path: 'topics/:tag.html',
      // layout to use for tag listing
      layout: 'tag.liquid',
      // provide posts sorted by 'date' (optional)
      sortBy: 'date',
      // sort direction (optional)
      reverse: true,
      // skip updating metalsmith's metadata object.
      // useful for improving performance on large blogs
      // (optional)
      skipMetadata: false,
      // Any options you want to pass to the [slug](https://github.com/dodo/node-slug) package.
      // Can also supply a custom slug function.
      // slug: function(tag) { return tag.toLowerCase() }
      slug: {mode: 'rfc3986'}
    },
    sass: {
      outputDir: 'assets/css',
      sourceMap: true,
      sourceMapEmbed: true
    },
    imagemin: {
      optimizationLevel: 4,
      progressive: true
    },
    htmlMinifier: {
      removeComments: false,
      removeEmptyAttributes: false
    },
    preMiddleware: false,
    postMiddleware: false
  };

  const options = deepAssign({}, DEFAULT_OPTIONS, config);

  // Config
  // --------------------------------------------------------------------------
  const m = new Metalsmith(options.basePath);

  // Metalsmith options
  // --------------------------------------------------------------------------
  m.clean(true);
  m.destination(config.destination || 'dist');

  // Object Metadata
  // --------------------------------------------------------------------------
  m.metadata(options.metadata);

  // File Metadata
  // --------------------------------------------------------------------------
  m.use(metadata(options.filedata));

  // Build Date
  // --------------------------------------------------------------------------
  m.use(date({ key: 'dateBuilt' }));

  // Firebase
  // --------------------------------------------------------------------------
  if (options.firebase) {
    m.use(firebase(options.firebase));
  }

  // Ignores
  // --------------------------------------------------------------------------
  m.use(ignore(options.ignore));

  // Drafts
  // --------------------------------------------------------------------------
  if (m.metadata().production) {
    m.use(drafts());
  }

  // Definitions
  // --------------------------------------------------------------------------
  m.use(define({ moment }));

  // Date
  // --------------------------------------------------------------------------
  m.use(jekyllDates());

  // Tags
  // --------------------------------------------------------------------------
  if (options.tags) {
    m.use(tags(options.tags));
  }

  // Code Highlighting
  // --------------------------------------------------------------------------
  m.use(metallic());

  // Markdown
  // --------------------------------------------------------------------------
  m.use(markdown(options.markdown));

  // Excerpts
  // --------------------------------------------------------------------------
  m.use(excerpts());

  // Attach Collections
  // --------------------------------------------------------------------------
  m.use(collections(options.collections));

  // Permalinks
  // --------------------------------------------------------------------------
  m.use(permalinks(options.permalinks));

  // Pagination
  // --------------------------------------------------------------------------
  if (options.pagination) {
    m.use(pagination(options.pagination));
  }

  // Styles
  // --------------------------------------------------------------------------
  if (m.metadata().production) {
    options.sass.outputStyle = 'compressed';
    options.sass.sourceMap = false;
    options.sass.sourceMapEmbed = false;
    m.use(sass(options.sass));
  } else {
    m.use(sass(options.sass));
  }
  m.use(autoprefixer());

  // Fingerprinting
  // --------------------------------------------------------------------------
  if (options.fingerprint) {
    m.use(fingerprint(options.fingerprint));
  }

  // Post-template Middleware
  // --------------------------------------------------------------------------
  if (options.preMiddleware) {
    for (const plugin in options.preMiddleware) {
      if (options.preMiddleware[plugin]) {
        m.use(options.preMiddleware[plugin]);
      }
    }
  }

  // Templates
  // --------------------------------------------------------------------------
  m.use(layouts(options.layouts));
  m.use(inPlace(options.inPlace));

  // Js
  // --------------------------------------------------------------------------
  if (options.webpack) {
    if (m.metadata().production) {
      m.use(webpack(options.webpack.prod));
    } else {
      m.use(webpack(options.webpack.dev));
    }
  }

  // Sitemap
  // --------------------------------------------------------------------------
  if (m.metadata().production && options.sitemap) {
    m.use(sitemap(options.sitemap));
  }

  // RSS Feed
  // --------------------------------------------------------------------------
  if (options.rss) {
    if (m.metadata().production) {
      m.use(rss(options.rss));
    }
  }

  // Production
  // --------------------------------------------------------------------------
  if (m.metadata().production) {
    m.use(imagemin(options.imagemin));
    m.use(htmlMinifier('*.html', options.htmlMinifier));
  }

  // Post-template Middleware
  // --------------------------------------------------------------------------
  if (options.postMiddleware) {
    for (const plugin in options.postMiddleware) {
      if (options.postMiddleware[plugin]) {
        m.use(options.postMiddleware[plugin]);
      }
    }
  }

  m.build(callback);

  return m;

}<commit_msg>fix(semantic-release): force semantic release<commit_after>import path             from 'path';
import fs               from 'fs';
import Metalsmith       from 'metalsmith';
import deepAssign       from 'deep-assign';
import collections      from 'metalsmith-collections';
import metadata         from 'metalsmith-metadata';
import markdown         from 'metalsmith-markdown';
import layouts          from 'metalsmith-layouts';
import inPlace          from 'metalsmith-in-place';
import permalinks       from 'metalsmith-permalinks';
import pagination       from 'metalsmith-pagination';
import excerpts         from 'metalsmith-excerpts';
import sass             from 'metalsmith-sass';
import moment           from 'moment';
import define           from 'metalsmith-define';
import jekyllDates      from 'metalsmith-jekyll-dates';
import autoprefixer     from 'metalsmith-autoprefixer';
import webpack          from 'metalsmith-webpack';
import ignore           from 'metalsmith-ignore';
import metallic         from 'metalsmith-metallic';
import tags             from 'metalsmith-tags';
import snippet          from 'metalsmith-snippet';
import blc              from 'metalsmith-broken-link-checker';
import date             from 'metalsmith-build-date';
// prod
import htmlMinifier     from 'metalsmith-html-minifier';
import fingerprint      from 'metalsmith-fingerprint';
import imagemin         from 'metalsmith-imagemin';
import sitemap          from 'metalsmith-sitemap';
import firebase         from 'metalsmith-firebase';
import rss              from 'metalsmith-rss';
import drafts           from 'metalsmith-drafts';

export default function (config = {}, callback) {

  const DEFAULT_OPTIONS = {
    metadata: {
      title: 'Metalpress',
      description: 'Create a blog with Metalpress.',
      url: 'https://metalpress.io',
      production: false
    },
    filedata: {},
    sitemap: false,
    rss: false,
    ignore: [
      'data/**',
      '_data/**',
      '_drafts/*.md',
      'templates/**',
      'lib/**',
      'lib/**/.gitignore',
      'lib/**/.bower.json',
      'lib/**/.jshintrc',
      'assets/js/**/!(.min).js'
    ],
    markdown: {
      gfm: true,
      tables: true
    },
    permalinks: {
      relative: false,
      pattern: ':title'
    },
    layouts: {
      engine: 'liquid',
      directory: 'templates/_layouts',
      includeDir: 'templates/_includes'
    },
    inPlace: {
      engine: 'liquid',
      pattern: '**/*.liquid',
      includeDir: 'templates/_includes'
    },
    fingerprint: {
      pattern: 'assets/css/main.css'
    },
    tags: {
      // yaml key for tag list in you pages
      handle: 'tags',
      // path for result pages
      path: 'topics/:tag.html',
      // layout to use for tag listing
      layout: 'tag.liquid',
      // provide posts sorted by 'date' (optional)
      sortBy: 'date',
      // sort direction (optional)
      reverse: true,
      // skip updating metalsmith's metadata object.
      // useful for improving performance on large blogs (optional)
      skipMetadata: false,
      // Any options you want to pass to the [slug](https://github.com/dodo/node-slug) package.
      // Can also supply a custom slug function.
      // slug: function(tag) { return tag.toLowerCase() }
      slug: {mode: 'rfc3986'}
    },
    sass: {
      outputDir: 'assets/css',
      sourceMap: true,
      sourceMapEmbed: true
    },
    imagemin: {
      optimizationLevel: 4,
      progressive: true
    },
    htmlMinifier: {
      removeComments: false,
      removeEmptyAttributes: false
    },
    preMiddleware: false,
    postMiddleware: false
  };

  const options = deepAssign({}, DEFAULT_OPTIONS, config);

  // Config
  // --------------------------------------------------------------------------
  const m = new Metalsmith(options.basePath);

  // Metalsmith options
  // --------------------------------------------------------------------------
  m.clean(true);
  m.destination(config.destination || 'dist');

  // Object Metadata
  // --------------------------------------------------------------------------
  m.metadata(options.metadata);

  // File Metadata
  // --------------------------------------------------------------------------
  m.use(metadata(options.filedata));

  // Build Date
  // --------------------------------------------------------------------------
  m.use(date({ key: 'dateBuilt' }));

  // Firebase
  // --------------------------------------------------------------------------
  if (options.firebase) {
    m.use(firebase(options.firebase));
  }

  // Ignores
  // --------------------------------------------------------------------------
  m.use(ignore(options.ignore));

  // Drafts
  // --------------------------------------------------------------------------
  if (m.metadata().production) {
    m.use(drafts());
  }

  // Definitions
  // --------------------------------------------------------------------------
  m.use(define({ moment }));

  // Date
  // --------------------------------------------------------------------------
  m.use(jekyllDates());

  // Tags
  // --------------------------------------------------------------------------
  if (options.tags) {
    m.use(tags(options.tags));
  }

  // Code Highlighting
  // --------------------------------------------------------------------------
  m.use(metallic());

  // Markdown
  // --------------------------------------------------------------------------
  m.use(markdown(options.markdown));

  // Excerpts
  // --------------------------------------------------------------------------
  m.use(excerpts());

  // Attach Collections
  // --------------------------------------------------------------------------
  m.use(collections(options.collections));

  // Permalinks
  // --------------------------------------------------------------------------
  m.use(permalinks(options.permalinks));

  // Pagination
  // --------------------------------------------------------------------------
  if (options.pagination) {
    m.use(pagination(options.pagination));
  }

  // Styles
  // --------------------------------------------------------------------------
  if (m.metadata().production) {
    options.sass.outputStyle = 'compressed';
    options.sass.sourceMap = false;
    options.sass.sourceMapEmbed = false;
    m.use(sass(options.sass));
  } else {
    m.use(sass(options.sass));
  }
  m.use(autoprefixer());

  // Fingerprinting
  // --------------------------------------------------------------------------
  if (options.fingerprint) {
    m.use(fingerprint(options.fingerprint));
  }

  // Post-template Middleware
  // --------------------------------------------------------------------------
  if (options.preMiddleware) {
    for (const plugin in options.preMiddleware) {
      if (options.preMiddleware[plugin]) {
        m.use(options.preMiddleware[plugin]);
      }
    }
  }

  // Templates
  // --------------------------------------------------------------------------
  m.use(layouts(options.layouts));
  m.use(inPlace(options.inPlace));

  // Js
  // --------------------------------------------------------------------------
  if (options.webpack) {
    if (m.metadata().production) {
      m.use(webpack(options.webpack.prod));
    } else {
      m.use(webpack(options.webpack.dev));
    }
  }

  // Sitemap
  // --------------------------------------------------------------------------
  if (m.metadata().production && options.sitemap) {
    m.use(sitemap(options.sitemap));
  }

  // RSS Feed
  // --------------------------------------------------------------------------
  if (options.rss) {
    if (m.metadata().production) {
      m.use(rss(options.rss));
    }
  }

  // Production
  // --------------------------------------------------------------------------
  if (m.metadata().production) {
    m.use(imagemin(options.imagemin));
    m.use(htmlMinifier('*.html', options.htmlMinifier));
  }

  // Post-template Middleware
  // --------------------------------------------------------------------------
  if (options.postMiddleware) {
    for (const plugin in options.postMiddleware) {
      if (options.postMiddleware[plugin]) {
        m.use(options.postMiddleware[plugin]);
      }
    }
  }

  m.build(callback);

  return m;

}<|endoftext|>


<commit_before>import './guard';
import hook from './hook';
import postcss from 'postcss';
import { dirname, join, parse, relative, resolve, sep } from 'path';
import { readFileSync } from 'fs';

import ExtractImports from 'postcss-modules-extract-imports';
import LocalByDefault from 'postcss-modules-local-by-default';
import Scope from 'postcss-modules-scope';
import Parser from './parser';

const escapedSeparator = sep.replace(/(.)/g, '\\$1');
const relativePathPattern = new RegExp(`^.{1,2}$|^.{1,2}${escapedSeparator}`);

const defaultRoot = process.cwd();
const tokensByFile = {};
let plugins = [LocalByDefault, ExtractImports, Scope];
let root = defaultRoot;
let importNr = 0;

/**
 * @param  {string}  pathname
 * @return {boolean}
 */
function isModule(pathname) {
  const parsed = parse(pathname);
  return !parsed.root && !relativePathPattern.test(parsed.dir);
}

/**
 * @param  {string}   sourceString The file content
 * @param  {string}   sourcePath
 * @param  {string}   trace
 * @param  {function} pathFetcher
 * @return {object}
 */
function load(sourceString, sourcePath, trace, pathFetcher) {
  const result = postcss(plugins.concat(new Parser({ pathFetcher, trace })))
    .process(sourceString, {from: sourcePath})
    .root;

  return result.tokens;
}

/**
 * @param  {string} _newPath
 * @param  {string} _relativeTo
 * @param  {string} _trace
 * @return {object}
 */
function fetch(_newPath, _relativeTo, _trace) {
  const newPath = _newPath.replace(/^["']|["']$/g, '');
  const trace = _trace || String.fromCharCode(importNr++);

  const relativeDir = dirname(_relativeTo);
  const rootRelativePath = resolve(relativeDir, newPath);
  let fileRelativePath = resolve(join(root, relativeDir), newPath);

  if (isModule(newPath)) {
    fileRelativePath = require.resolve(newPath);
  }

  const tokens = tokensByFile[fileRelativePath];
  if (tokens) {
    return tokens;
  }

  const source = readFileSync(fileRelativePath, 'utf-8');
  const exportTokens = load(source, rootRelativePath, trace, fetch);

  tokensByFile[fileRelativePath] = exportTokens;

  return exportTokens;
}

hook(filename => fetch(`.${sep}${relative(root, filename)}`, '/'));

/**
 * @param  {object} opts
 * @param  {array}  opts.u
 * @param  {array}  opts.use
 */
export default function configure(opts = {}) {
  const customPlugins = opts.u || opts.use;
  plugins = Array.isArray(customPlugins)
    ? customPlugins
    : [LocalByDefault, ExtractImports, Scope];

  root = opts.root && typeof opts.root === 'string'
    ? opts.root
    : defaultRoot;
}
<commit_msg>getting back injectableSource<commit_after>import './guard';
import hook from './hook';
import postcss from 'postcss';
import { dirname, join, parse, relative, resolve, sep } from 'path';
import { readFileSync } from 'fs';

import ExtractImports from 'postcss-modules-extract-imports';
import LocalByDefault from 'postcss-modules-local-by-default';
import Scope from 'postcss-modules-scope';
import Parser from './parser';

const escapedSeparator = sep.replace(/(.)/g, '\\$1');
const relativePathPattern = new RegExp(`^.{1,2}$|^.{1,2}${escapedSeparator}`);

const defaultRoot = process.cwd();
const tokensByFile = {};
let plugins = [LocalByDefault, ExtractImports, Scope];
let root = defaultRoot;
let importNr = 0;

/**
 * @param  {string}  pathname
 * @return {boolean}
 */
function isModule(pathname) {
  const parsed = parse(pathname);
  return !parsed.root && !relativePathPattern.test(parsed.dir);
}

/**
 * @param  {string}   sourceString The file content
 * @param  {string}   sourcePath
 * @param  {string}   trace
 * @param  {function} pathFetcher
 * @return {object}
 */
function load(sourceString, sourcePath, trace, pathFetcher) {
  const lazyResult = postcss(plugins.concat(new Parser({ pathFetcher, trace })))
    .process(sourceString, {from: sourcePath});

  return { injectableSource: lazyResult.css, exportTokens: lazyResult.root.tokens };;
}

/**
 * @param  {string} _newPath
 * @param  {string} _relativeTo
 * @param  {string} _trace
 * @return {object}
 */
function fetch(_newPath, _relativeTo, _trace) {
  const newPath = _newPath.replace(/^["']|["']$/g, '');
  const trace = _trace || String.fromCharCode(importNr++);

  const relativeDir = dirname(_relativeTo);
  const rootRelativePath = resolve(relativeDir, newPath);
  let fileRelativePath = resolve(join(root, relativeDir), newPath);

  if (isModule(newPath)) {
    fileRelativePath = require.resolve(newPath);
  }

  const tokens = tokensByFile[fileRelativePath];
  if (tokens) {
    return tokens;
  }

  const source = readFileSync(fileRelativePath, 'utf-8');
  const { exportTokens, injectableSource } = load(source, rootRelativePath, trace, fetch);

  tokensByFile[fileRelativePath] = exportTokens;

  return exportTokens;
}

hook(filename => fetch(`.${sep}${relative(root, filename)}`, '/'));

/**
 * @param  {object} opts
 * @param  {array}  opts.u
 * @param  {array}  opts.use
 */
export default function configure(opts = {}) {
  const customPlugins = opts.u || opts.use;
  plugins = Array.isArray(customPlugins)
    ? customPlugins
    : [LocalByDefault, ExtractImports, Scope];

  root = opts.root && typeof opts.root === 'string'
    ? opts.root
    : defaultRoot;
}
<|endoftext|>


<commit_before>// Copyright 2018 Google LLC
//
// 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
//
//     https://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.

/**
 * @namespace google
 */
/**
 * @namespace google.cloud
 */
/**
 * @namespace google.cloud.tasks
 */
/**
 * @namespace google.cloud.tasks.v2beta2
 */
/**
 * @namespace google.cloud.tasks.v2beta3
 */
/**
 * @namespace google.protobuf
 */
/**
 * @namespace google.rpc
 */
/**
 * @namespace google.type
 */

'use strict';

// Import the clients for each version supported by this package.
const gapic = Object.freeze({
  v2beta2: require('./v2beta2'),
  v2beta3: require('./v2beta3'),
});

/**
 * The `tasks` package has the following named exports:
 *
 * - `CloudTasksClient` - Reference to
 *   {@link v2beta2.CloudTasksClient}
 * - `v2beta2` - This is used for selecting or pinning a
 *   particular backend service version. It exports:
 *     - `CloudTasksClient` - Reference to
 *       {@link v2beta2.CloudTasksClient}
 *
 * @module {object} tasks
 * @alias nodejs-tasks
 *
 * @example
Install the client library with npm:

 * npm install --save tasks
 *
 * @example
Import the client library:

 * const tasks = require('@google-cloud/tasks');
 *
 * @example
Create a client that uses Application Default Credentials (ADC):

 * const client = new tasks.CloudTasksClient();
 *
 * @example
Create a client with explicit credentials:

 * const client = new tasks.CloudTasksClient({
 *   projectId: 'your-project-id',
 *   keyFilename: '/path/to/keyfile.json',
 * });
 */

/**
 * @type {object}
 * @property {constructor} CloudTasksClient
 *   Reference to {@link v2beta3.CloudTasksClient}
 */
module.exports = gapic.v2beta2;

/**
 * @type {object}
 * @property {constructor} CloudTasksClient
 *   Reference to {@link v2beta2.CloudTasksClient}
 */
module.exports.v2beta2 = gapic.v2beta2;

/**
 * @type {object}
 * @property {constructor} CloudTasksClient
 *   Reference to {@link v2beta2.CloudTasksClient}
 */
module.exports.v2beta3 = gapic.v2beta3;

// Alias `module.exports` as `module.exports.default`, for future-proofing.
module.exports.default = Object.assign({}, module.exports);
<commit_msg>feat: using v2beta3 by default<commit_after>// Copyright 2018 Google LLC
//
// 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
//
//     https://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.

/**
 * @namespace google
 */
/**
 * @namespace google.cloud
 */
/**
 * @namespace google.cloud.tasks
 */
/**
 * @namespace google.cloud.tasks.v2beta2
 */
/**
 * @namespace google.cloud.tasks.v2beta3
 */
/**
 * @namespace google.protobuf
 */
/**
 * @namespace google.rpc
 */
/**
 * @namespace google.type
 */

'use strict';

// Import the clients for each version supported by this package.
const gapic = Object.freeze({
  v2beta2: require('./v2beta2'),
  v2beta3: require('./v2beta3'),
});

/**
 * The `tasks` package has the following named exports:
 *
 * - `CloudTasksClient` - Reference to
 *   {@link v2beta2.CloudTasksClient}
 * - `v2beta2` - This is used for selecting or pinning a
 *   particular backend service version. It exports:
 *     - `CloudTasksClient` - Reference to
 *       {@link v2beta2.CloudTasksClient}
 *
 * @module {object} tasks
 * @alias nodejs-tasks
 *
 * @example
Install the client library with npm:

 * npm install --save tasks
 *
 * @example
Import the client library:

 * const tasks = require('@google-cloud/tasks');
 *
 * @example
Create a client that uses Application Default Credentials (ADC):

 * const client = new tasks.CloudTasksClient();
 *
 * @example
Create a client with explicit credentials:

 * const client = new tasks.CloudTasksClient({
 *   projectId: 'your-project-id',
 *   keyFilename: '/path/to/keyfile.json',
 * });
 */

/**
 * @type {object}
 * @property {constructor} CloudTasksClient
 *   Reference to {@link v2beta3.CloudTasksClient}
 */
module.exports = gapic.v2beta3;

/**
 * @type {object}
 * @property {constructor} CloudTasksClient
 *   Reference to {@link v2beta2.CloudTasksClient}
 */
module.exports.v2beta2 = gapic.v2beta2;

/**
 * @type {object}
 * @property {constructor} CloudTasksClient
 *   Reference to {@link v2beta2.CloudTasksClient}
 */
module.exports.v2beta3 = gapic.v2beta3;

// Alias `module.exports` as `module.exports.default`, for future-proofing.
module.exports.default = Object.assign({}, module.exports);
<|endoftext|>


<commit_before>var parseXmlString = require('xml2js').parseString;
var https = require('https');
var querystring = require('querystring');

var roux = {};

roux.request = function(key, action, data, errCallback, callback) {
	var rouxRequest = "";
	rouxRequest += "<request><key>";
	rouxRequest += "";
	rouxRequest += "</key><action>";
	rouxRequest += action;
	rouxRequest += "</action>";
	rouxRequest += data;
	rouxRequest += "</request>";

	var post_data = querystring.stringify({
		'rouxRequest': rouxRequest
	});

	var post_options = {
		host: 'schedules.dalton.org',
		port: '443',
		path: '/roux/index.php',
		method: 'POST',
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
			'Content-Length': post_data.length
		}
	};

	var post_req = https.request(post_options, function(hRes) {
		hRes.setEncoding('utf8');
		hRes.on('data', function (chunk) {
			parseXmlString(chunk, function(err, data) {
				if (err) {
					errCallback(err);
					return;
				}
				if (data["response"]["result"][0]["$"]["status"] != 200) {
					errCallback("The username or password was incorrect!");
					return;
				}
				callback(data);
			});
		});
	});

	post_req.write(post_data);
	post_req.end();
};

module.exports = roux;
<commit_msg>revenge of the wheye<commit_after>var parseXmlString = require('xml2js').parseString;
var https = require('https');
var querystring = require('querystring');

var roux = {};

roux.request = function(key, action, data, errCallback, callback) {
	var rouxRequest = "";
	rouxRequest += "<request><key>";
	rouxRequest += "";
	rouxRequest += "</key><action>";
	rouxRequest += action;
	rouxRequest += "</action>";
	rouxRequest += data;
	rouxRequest += "</request>";

	var post_data = querystring.stringify({
		'rouxRequest': rouxRequest
	});

	var post_options = {
		host: 'schedules.dalton.org',
		port: '443',
		path: '/roux/index.php',
		method: 'POST',
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
			'Content-Length': post_data.length
		}
	};

	var post_req = https.request(post_options, function(hRes) {
		hRes.setEncoding('utf8');
		hRes.on('data', function (chunk) {
			parseXmlString(chunk, function(err, data) {
				if (err) {
					errCallback(err);
					return;
				}
				if (data["response"]["result"][0]["$"]["status"] != 200) {
					/*errCallback("The username or password was incorrect!");*/
					errCallback(data);
					return;
				}
				callback(data);
			});
		});
	});

	post_req.write(post_data);
	post_req.end();
};

module.exports = roux;
<|endoftext|>


<commit_before>import PropTypes from 'proptypes';
import { render as preactRender, h, Component as PreactComponent, hooks } from 'preact';

const DEV = !isProd();

function isProd() {
	let prod;
	try { prod = process.env.NODE_ENV==='production'; } catch(e) {}
	return !!prod;
}

// proxy render() since React returns a Component reference.
function render(vnode, parent, callback) {
	let out = preactRender(vnode, parent);
	if (typeof callback==='function') callback();
	return out && out._component;
}

// This API is completely unnecessary for Preact, so it's basically passthrough.
let Children = {
	map(children, fn, ctx) {
		if (ctx && ctx!==children) fn = fn.bind(ctx);
		return children.map(fn);
	},
	forEach(children, fn, ctx) {
		if (ctx && ctx!==children) fn = fn.bind(ctx);
		children.forEach(fn);
	},
	count(children) {
		return children.length;
	},
	only(children) {
		if (children.length!==1) throw new Error('Children.only() expects only one child.');
		return children[0];
	},
	toArray(children) {
		return children;
	}
};

let createElement = (...args) => {
	let vnode = h(...args);
	applyClassName(vnode);
	return vnode;
};

let applyClassName = ({ attributes }) => {
	if (!attributes) return;
	let cl = attributes.className || attributes.class;
	if (cl) attributes.className = cl;
};

let extend = (base, ...objs) => {
	for (let i=0; i<objs.length; i++) {
		for (let key in objs[i]) {
			if (objs[i].hasOwnProperty(key)) {
				let v = objs[i][key];
				if (v!==null && v!==undefined) {
					base[key] = v;
				}
			}
		}
	}
	return base;
};

let findDOMNode = component => component.base || component;

function F(){}

let createClass = obj => {
	let cl = function() {
		Component.call(this);
		extend(this, obj);
		bindAll(this);
	};
	F.prototype = Component.prototype;
	cl.prototype = new F();
	cl.prototype.constructor = cl;
	return cl;
};

let bindAll = ctx => {
	for (let i in ctx) {
		let v = ctx[i];
		if (typeof v==='function' && !v.__bound) {
			(ctx[i] = v.bind(ctx)).__bound = true;
		}
	}
};

class Component extends PreactComponent {
	constructor(...args) {
		super(...args);
		this._stateUpdateCallbacks = [];
	}

	getDOMNode() {
		return this.base;
	}

	setState(state, callback) {
		super.setState(state);
		if (typeof callback==='function') {
			this._stateUpdateCallbacks.push(callback);
			callback();
		}
	}

	componentWillReceiveProps(props) {
		let defaultProps = this.defaultProps || this.constructor.defaultProps;
		if (defaultProps) {
			props = extend({}, defaultProps, props);
		}

		// add proptype checking
		if (DEV) {
			let propTypes = this.propTypes || this.constructor.propTypes;
			if (propTypes) {
				for (let prop in propTypes) {
					if (propTypes.hasOwnProperty(prop) && typeof propTypes[prop]==='function') {
						let err = propTypes[prop](props, prop, this.constructor.name, 'prop');
						if (err) throw err;
					}
				}
			}
		}
	}

	_render(...args) {
		let ret = super._render(...args);

		if (this.props.ref && this.base.getAttribute('ref')!==this.props.ref) {
			this.base.setAttribute('ref', this.props.ref);
		}

		// add refs
		let refs = this.base.querySelectorAll('[ref]');
		this.refs = {};
		for (let i=refs.length; i--; ) {
			this.refs[refs[i].getAttribute('ref')] = refs[i]._component || refs[i];
		}

		let cb = this._stateUpdateCallbacks;
		if (cb) {
			this._stateUpdateCallbacks = [];
			for (let i=0; i<cb.length; i++) cb[i]();
		}

		return ret;
	}
}

export { PropTypes, Children, render, createClass, createElement, findDOMNode, Component };
export default { PropTypes, Children, render, createClass, createElement, findDOMNode, Component };
<commit_msg>Preact 4 compat (prelim)<commit_after>import PropTypes from 'proptypes';
import { render as preactRender, h, Component as PreactComponent, hooks } from 'preact';

const DEV = !isProd();

function isProd() {
	let prod;
	try { prod = process.env.NODE_ENV==='production'; } catch(e) {}
	return !!prod;
}

// proxy render() since React returns a Component reference.
function render(vnode, parent, callback) {
	let out = preactRender(vnode, parent);
	if (typeof callback==='function') callback();
	return out && out._component;
}

// This API is completely unnecessary for Preact, so it's basically passthrough.
let Children = {
	map(children, fn, ctx) {
		if (ctx && ctx!==children) fn = fn.bind(ctx);
		return children.map(fn);
	},
	forEach(children, fn, ctx) {
		if (ctx && ctx!==children) fn = fn.bind(ctx);
		children.forEach(fn);
	},
	count(children) {
		return children.length;
	},
	only(children) {
		if (children.length!==1) throw new Error('Children.only() expects only one child.');
		return children[0];
	},
	toArray(children) {
		return children;
	}
};

let createElement = (...args) => {
	let vnode = h(...args);
	applyClassName(vnode);
	return vnode;
};

let applyClassName = ({ attributes }) => {
	if (!attributes) return;
	let cl = attributes.className || attributes.class;
	if (cl) attributes.className = cl;
};

let extend = (base, ...objs) => {
	for (let i=0; i<objs.length; i++) {
		for (let key in objs[i]) {
			if (objs[i].hasOwnProperty(key)) {
				let v = objs[i][key];
				if (v!==null && v!==undefined) {
					base[key] = v;
				}
			}
		}
	}
	return base;
};

let findDOMNode = component => component.base || component;

function F(){}

let createClass = obj => {
	let cl = function() {
		Component.call(this);
		extend(this, obj);
		bindAll(this);
	};
	F.prototype = Component.prototype;
	cl.prototype = new F();
	cl.prototype.constructor = cl;
	return cl;
};

let bindAll = ctx => {
	for (let i in ctx) {
		let v = ctx[i];
		if (typeof v==='function' && !v.__bound) {
			(ctx[i] = v.bind(ctx)).__bound = true;
		}
	}
};

class Component extends PreactComponent {
	constructor(...args) {
		super(...args);
		this._stateUpdateCallbacks = [];
	}

	getDOMNode() {
		return this.base;
	}

	componentWillReceiveProps(props) {
		let defaultProps = this.defaultProps || this.constructor.defaultProps;
		if (defaultProps) {
			props = extend({}, defaultProps, props);
		}

		// add proptype checking
		if (DEV) {
			let propTypes = this.propTypes || this.constructor.propTypes;
			if (propTypes) {
				for (let prop in propTypes) {
					if (propTypes.hasOwnProperty(prop) && typeof propTypes[prop]==='function') {
						let err = propTypes[prop](props, prop, this.constructor.name, 'prop');
						if (err) throw err;
					}
				}
			}
		}
	}

	componentDidUpdate() {
		if (this.props.ref && this.base.getAttribute('ref')!==this.props.ref) {
			this.base.setAttribute('ref', this.props.ref);
		}

		// add refs
		let refs = this.base.querySelectorAll('[ref]');
		this.refs = {};
		for (let i=refs.length; i--; ) {
			this.refs[refs[i].getAttribute('ref')] = refs[i]._component || refs[i];
		}

		return ret;
	}
}

export { PropTypes, Children, render, createClass, createElement, findDOMNode, Component };
export default { PropTypes, Children, render, createClass, createElement, findDOMNode, Component };
<|endoftext|>


<commit_before>/**
 * We.js main file, load we.js core and features
 */

// Module dependencies.
const http = require('http'),
      _ = require('lodash'),
      path = require('path'),
      staticConfig = require('./staticConfig'),
      Database = require('./Database'),
      Hooks = require('./Hooks'),
      PluginManager = require('./PluginManager'),
      Router = require('./Router'),
      Sanitizer = require('./Sanitizer'),
      EventEmiter = require('events'),
      { readFileSync, writeFileSync, writeFile } = require('fs');

/**
 * We.js object
 *
 * @type {Object}
 */
function We (options) {
  if (!options) options = {};

  const we = this;

  this.packageJSON = require('../package.json');

  this.config = options;

  this.childProcesses = [];

  this.plugins = {};
  this.pluginPaths = [];
  this.pluginNames = [];
  // controllers
  this.controllers = {};

  this.projectPath = options.projectPath || process.cwd();

  this.projectPackageJSON = require(path.resolve(this.projectPath, 'package.json'));

  this.projectConfigFolder = options.projectConfigFolder || path.join(this.projectPath, 'config');

  // start configs with static configs
  this.config = staticConfig(this.projectPath, this);
  // enviroment config prod | dev | test
  we.env = options.env || require('./getEnv.js')();
  // winston logger
  we.log = require('./log')(we);
  // hooks and events
  we.hooks = new Hooks();

  we.events = new EventEmiter();
  // we.js events is controlled then we will use an max of 70 listenners in every event:
  we.events.setMaxListeners(70);
  // we.js sanitizer
  we.sanitizer = new Sanitizer(this);
  // The we.js router
  we.router = new Router(this);
  // we.js prototypes
  we.class = {
    Controller: require('./class/Controller.js'),
    Theme: require('./class/Theme.js')(we),
    Plugin: require('./class/Plugin.js')(we)
  };
  // database logic and models is avaible in we.db.models
  we.db = new Database(this);
  // - init database
  we.db.defaultConnection = we.db.connect(we.env);
  //set for more compatbility with sequelize docs
  we.db.sequelize = we.db.defaultConnection;
  // plugin manager and plugins vars
  we.pluginManager = new PluginManager(this);

  switch (we.config.bootstrapMode) {
    case 'install':
    case 'installation':
    case 'update':
      we.hooks.on('bootstrap', [
        we.bootstrapFunctions.checkDBConnection,
        we.bootstrapFunctions.loadCoreFeatures,
        we.bootstrapFunctions.loadPluginFeatures,
        we.bootstrapFunctions.loadTemplateCache,
        we.bootstrapFunctions.instantiateModels,
        we.bootstrapFunctions.syncModels,
        we.bootstrapFunctions.loadControllers,
        we.bootstrapFunctions.initI18n,
        we.bootstrapFunctions.installAndRegisterPlugins
      ]);
      break;
    case 'complete':
    case 'full':
    case 'test':
      // full load, usefull for tests
      we.hooks.on('bootstrap', [
        we.bootstrapFunctions.checkDBConnection,
        we.bootstrapFunctions.loadCoreFeatures,
        we.bootstrapFunctions.loadPluginFeatures,
        we.bootstrapFunctions.loadTemplateCache,
        we.bootstrapFunctions.instantiateModels,
        we.bootstrapFunctions.syncModels,
        we.bootstrapFunctions.loadControllers,
        we.bootstrapFunctions.initI18n,
        we.bootstrapFunctions.installAndRegisterPlugins,
        we.bootstrapFunctions.setExpressApp,
        we.bootstrapFunctions.passport,
        we.bootstrapFunctions.createDefaultFolders,
        we.bootstrapFunctions.registerAllViewTemplates,
        we.bootstrapFunctions.mergeRoutes,
        we.bootstrapFunctions.bindResources,
        we.bootstrapFunctions.bindRoutes
      ]);
      break;
    default:
      // defaults to load for run
      we.hooks.on('bootstrap', [
        we.bootstrapFunctions.checkDBConnection,
        we.bootstrapFunctions.loadCoreFeatures,
        we.bootstrapFunctions.loadPluginFeatures,
        we.bootstrapFunctions.loadTemplateCache,
        we.bootstrapFunctions.instantiateModels,
        we.bootstrapFunctions.syncModels,
        we.bootstrapFunctions.loadControllers,
        we.bootstrapFunctions.initI18n,
        we.bootstrapFunctions.installAndRegisterPlugins,
        we.bootstrapFunctions.setExpressApp,
        we.bootstrapFunctions.passport,
        we.bootstrapFunctions.createDefaultFolders,
        we.bootstrapFunctions.registerAllViewTemplates,
        we.bootstrapFunctions.mergeRoutes,
        we.bootstrapFunctions.bindResources,
        we.bootstrapFunctions.bindRoutes
      ]);
  }
}

We.prototype = {
  /**
   * Set config in config/configuration.json file
   *
   * @param {String}   variable path to the variable
   * @param {String}   value
   * @param {Function} cb       callback
   */
  setConfig(variable, value, cb) {
    if (!cb) cb = function(){};

    let cJSON,
        cFGpath = path.join(this.projectPath, '/config/configuration.json');

    try {
      cJSON = JSON.parse(readFileSync(cFGpath));
    } catch(e) {
      if (e.code == 'ENOENT') {
        writeFileSync(cFGpath, '{}');
        cJSON = {};
      } else {
        return cb(e);
      }
    }

    if (value == 'true') value = true;
    if (value == 'false') value = false;

    _.set(cJSON, variable, value);

    writeFile(cFGpath, JSON.stringify(cJSON, null, 2), cb);
  },

  /**
   * Unset config in config/configuration.json file
   *
   * @param {String}   variable path to the variable
   * @param {String}   value
   * @param {Function} cb       callback
   */
  unSetConfig(variable, cb) {
    let cJSON,
        cFGpath = path.join(this.projectPath, '/config/configuration.json');

    try {
      cJSON = JSON.parse(readFileSync(cFGpath));
    } catch(e) {
      if (e.code == 'ENOENT') {
        writeFileSync(cFGpath, '{}');
        cJSON = {};
      } else {
        return cb(e);
      }
    }

    _.unset(cJSON, variable);

    writeFile(cFGpath, JSON.stringify(cJSON, null, 2), cb);
  },
  // set bootstrap functions
  bootstrapFunctions: require('./bootstrapFunctions'),
  // flag to check if this we.js instance did the bootstrap
  bootstrapStarted: false,
  // flag to check if needs restart
  needsRestart: false,
  // we.utils.async, we.utils._ ... see the ./utils file
  utils: require('./utils'),
  // load we.js responses
  responses: require('./responses'),
  // save we-core path to plugin.js for update e install process
  weCorePluginfile: path.resolve(__dirname, '../') + '/plugin.js',
  //Overide default toString and inspect to custom infos in we.js object
  inspect() {
    return '\nWe.js ;)\n';
  },
  toString() {
    return this.inspect();
  },
  // client side config generator
  getAppBootstrapConfig: require('./staticConfig/getAppBootstrapConfig.js'),

  /**
   * Bootstrap and initialize the app
   *
   * @param  {Object}   configOnRun optional
   * @param  {Function} cb          callback to run after load we.js
   */
  bootstrap(configOnRun, cb) {
    const we = this;
    // only bootstrap we.js one time
    if (we.bootstrapStarted) throw new Error('We.js already did bootstrap');

    we.bootstrapStarted = true;
    // configsOnRun object is optional
    if (!cb) {
      cb = configOnRun;
      configOnRun = null;
    }
    // configs on run extends default and file configs
    if (configOnRun) _.merge(we.config, configOnRun);

    // run the bootstrap hook
    we.hooks.trigger('bootstrap', we, function bootstrapDone (err) {
      if (err) {
        console.log('Error on bootstrap: ');
        throw err;
      }

      we.events.emit('we:bootstrap:done', we);

      we.log.debug('We.js bootstrap done');
      // set pm2 gracefullReload:
      we.setPM2grShutdownFN(we);

      return cb(null, we);
    });
  },

  /**
   * Start we.js server (express)
   * use after we.bootstrap
   *
   * @param  {Function} cb    callback how returns with cb(err);
   */
  startServer(cb) {
    if (!cb) cb = function(){}; // cb is optional

    let we = this;

    we.hooks.trigger('we:server:before:start' ,we ,function afterRunBeforeServerStart (err) {
      if (err) return cb(err);
      /**
       * Get port from environment and store in Express.
       */
      let port = normalizePort(we.config.port);
      we.express.set('port', port);

      /**
       * Create HTTP server with suport to url alias rewrite
       */
      const server = http.createServer(function onCreateServer (req, res){
        req.we = we;

        // suport for we.js widget API
        // install we-plugin-widget to enable this feature
        if (req.headers && req.headers['we-widget-action'] && req.method == 'POST') {
          req.isWidgetAction = true;
          req.originalMethod = req.method;
          req.method = 'GET'; // widgets only are associated to get routes
        }

        // parse extension if not is public folder
        if (!we.router.isPublicFolder(req.url)) {
          req.extension = we.router.splitExtensionFromURL(req.url);

          if (req.extension) {
            let format = we.utils.mime.getType(req.extension);

            if (req.we.config.responseTypes.includes(format)) {
              // update the header response format with extension format
              req.headers.accept = format;
              // update the old url
              req.url = req.url.replace('.'+req.extension, '');
            }
          }
        }
        // install we-plugin-url-alias to enable alias feature
        if (we.plugins['we-plugin-url-alias'] && we.config.enableUrlAlias) {
          we.router.alias.httpHandler.bind(this)(req, res);
        } else {
          we.express.bind(this)(req, res);
        }
      });

      we.events.emit('we:server:after:create', { we: we, server: server });

      /**
       * Listen on provided port, on all network interfaces.
       */

      // catch 404 and forward to error handler
      we.express.use(function routeNotFound (req, res) {
        we.log.debug('Route not found:', req.path);
        // var err = new Error('Not Found');
        // err.status = 404;
        return res.notFound();
      });

      server.listen(port);
      server.on('error', onError);
      server.on('listening', onListening);
      /**
       * Normalize a port into a number, string, or false.
       */
      function normalizePort (val) {
        let port = parseInt(val, 10);

        if (isNaN(port)) {
          // named pipe
          return val;
        }

        if (port >= 0) {
          // port number
          return port;
        }

        return false;
      }

      /**
       * Event listener for HTTP server "error" event.
       */
      function onError (error) {
        if (error.syscall !== 'listen') {
          throw error;
        }

        let bind = typeof port === 'string'
          ? 'Pipe ' + port
          : 'Port ' + port;

        // handle specific listen errors with friendly messages
        switch (error.code) {
          case 'EACCES':
            console.error(bind + ' requires elevated privileges');
            process.exit(1);
            break;
          case 'EADDRINUSE':
            console.error(bind + ' is already in use');
            process.exit(1);
            break;
          default:
            throw error;
        }
      }
      /**
       * Event listener for HTTP server "listening" event.
       */
      function onListening () {
        let addr = server.address(),
            bind = typeof addr === 'string'
          ? 'pipe ' + addr
          : 'port ' + addr.port;
        we.log.info('Run in '+we.env+' enviroment and listening on ' + bind);

        if (process.send) {
          process.send('ready');
        }
      }
      // save the current http server
      we.http = server;

      // express error handlers
      // will print stacktrace
      we.express.use(function onExpressError (err, req, res, next) {
        we.log.error('onExpressError:Error on:', req.path, err);
        res.serverError(err);
      });

      we.hooks.trigger('we:server:after:start',we, function afterHookAfterStart (err) {
        cb(err, we);
      });
    });
  },

  /**
   * Bootstrap and Start we.js server
   *
   * @param  {Object}   cfgs configs (optional)
   * @param  {Function} cb   callback
   */
  go(cfgs, cb) {
    if (!cb) {
      cb = cfgs;
      cfgs = {};
    }

    this.bootstrap(cfgs, function afterBootstrapOnWeGo (err, we) {
      if (err) throw err;
      we.startServer(cb);
    });
  },

  /**
   * Turn off process function
   *
   * @param  {Function} cb callback
   */
  exit(cb) {
    this.isExiting = true;
    // close db connection
    if (this.db.defaultConnection) {
      this.db.defaultConnection.close();
    }
    // close all loggers and wait for end writes
    this.log.closeAllLoggersAndDisconnect(this, cb);
  },

  /**
   * Helper function to delete (unpoint) pointers from response for help GC
   */
  freeResponseMemory(req, res) {
    delete res.locals.req;
    delete res.locals.regions;
    delete res.locals.Model;
    delete res.locals.body;
    delete res.locals.layoutHtml;
  },

  /**
   * Run all plugin and project cron tasks
   *
   * @param  {Function} cb callback
   */
  runCron(cb) {
    this.cron = require('./cron');
    this.cron.loadAndRunAllTasks(this, cb);
  },

  /**
   * set pm2 gracefullReload
   */
  setPM2grShutdownFN(we) {
    // old/windows version:
    process.on('message', (msg)=> {
      if (msg === 'shutdown') {
        // disconect, and exit
        we.exit( (err)=> { process.exit(err ? 1 : 0); });
      }
    });
    // new version:
    process.on('SIGINT', ()=> {
      we.exit( (err)=> { process.exit(err ? 1 : 0); });
    });
  }
};

module.exports = We;<commit_msg>disable uneed Promise wForgottenReturn warning<commit_after>/**
 * We.js main file, load we.js core and features
 */

// Module dependencies.
const http = require('http'),
      _ = require('lodash'),
      path = require('path'),
      staticConfig = require('./staticConfig'),
      Database = require('./Database'),
      Hooks = require('./Hooks'),
      PluginManager = require('./PluginManager'),
      Router = require('./Router'),
      Sanitizer = require('./Sanitizer'),
      EventEmiter = require('events'),
      { readFileSync, writeFileSync, writeFile } = require('fs');

/**
 * We.js object
 *
 * @type {Object}
 */
function We (options) {
  if (!options) options = {};

  const we = this;

  this.packageJSON = require('../package.json');

  this.config = options;

  this.childProcesses = [];

  this.plugins = {};
  this.pluginPaths = [];
  this.pluginNames = [];
  // controllers
  this.controllers = {};

  this.projectPath = options.projectPath || process.cwd();

  this.projectPackageJSON = require(path.resolve(this.projectPath, 'package.json'));

  this.projectConfigFolder = options.projectConfigFolder || path.join(this.projectPath, 'config');

  // start configs with static configs
  this.config = staticConfig(this.projectPath, this);
  // enviroment config prod | dev | test
  we.env = options.env || require('./getEnv.js')();
  // winston logger
  we.log = require('./log')(we);
  // hooks and events
  we.hooks = new Hooks();

  we.events = new EventEmiter();
  // we.js events is controlled then we will use an max of 70 listenners in every event:
  we.events.setMaxListeners(70);
  // we.js sanitizer
  we.sanitizer = new Sanitizer(this);
  // The we.js router
  we.router = new Router(this);
  // we.js prototypes
  we.class = {
    Controller: require('./class/Controller.js'),
    Theme: require('./class/Theme.js')(we),
    Plugin: require('./class/Plugin.js')(we)
  };
  // database logic and models is avaible in we.db.models
  we.db = new Database(this);
  // - init database
  we.db.defaultConnection = we.db.connect(we.env);
  //set for more compatbility with sequelize docs
  we.db.sequelize = we.db.defaultConnection;
  // plugin manager and plugins vars
  we.pluginManager = new PluginManager(this);

  // promise settings (Bluebird):
  if (Promise.config) {
    Promise.config({
      // Enables all warnings except forgotten return statements.
      warnings: { wForgottenReturn: false }
    });
  }

  switch (we.config.bootstrapMode) {
    case 'install':
    case 'installation':
    case 'update':
      we.hooks.on('bootstrap', [
        we.bootstrapFunctions.checkDBConnection,
        we.bootstrapFunctions.loadCoreFeatures,
        we.bootstrapFunctions.loadPluginFeatures,
        we.bootstrapFunctions.loadTemplateCache,
        we.bootstrapFunctions.instantiateModels,
        we.bootstrapFunctions.syncModels,
        we.bootstrapFunctions.loadControllers,
        we.bootstrapFunctions.initI18n,
        we.bootstrapFunctions.installAndRegisterPlugins
      ]);
      break;
    case 'complete':
    case 'full':
    case 'test':
      // full load, usefull for tests
      we.hooks.on('bootstrap', [
        we.bootstrapFunctions.checkDBConnection,
        we.bootstrapFunctions.loadCoreFeatures,
        we.bootstrapFunctions.loadPluginFeatures,
        we.bootstrapFunctions.loadTemplateCache,
        we.bootstrapFunctions.instantiateModels,
        we.bootstrapFunctions.syncModels,
        we.bootstrapFunctions.loadControllers,
        we.bootstrapFunctions.initI18n,
        we.bootstrapFunctions.installAndRegisterPlugins,
        we.bootstrapFunctions.setExpressApp,
        we.bootstrapFunctions.passport,
        we.bootstrapFunctions.createDefaultFolders,
        we.bootstrapFunctions.registerAllViewTemplates,
        we.bootstrapFunctions.mergeRoutes,
        we.bootstrapFunctions.bindResources,
        we.bootstrapFunctions.bindRoutes
      ]);
      break;
    default:
      // defaults to load for run
      we.hooks.on('bootstrap', [
        we.bootstrapFunctions.checkDBConnection,
        we.bootstrapFunctions.loadCoreFeatures,
        we.bootstrapFunctions.loadPluginFeatures,
        we.bootstrapFunctions.loadTemplateCache,
        we.bootstrapFunctions.instantiateModels,
        we.bootstrapFunctions.syncModels,
        we.bootstrapFunctions.loadControllers,
        we.bootstrapFunctions.initI18n,
        we.bootstrapFunctions.installAndRegisterPlugins,
        we.bootstrapFunctions.setExpressApp,
        we.bootstrapFunctions.passport,
        we.bootstrapFunctions.createDefaultFolders,
        we.bootstrapFunctions.registerAllViewTemplates,
        we.bootstrapFunctions.mergeRoutes,
        we.bootstrapFunctions.bindResources,
        we.bootstrapFunctions.bindRoutes
      ]);
  }
}

We.prototype = {
  /**
   * Set config in config/configuration.json file
   *
   * @param {String}   variable path to the variable
   * @param {String}   value
   * @param {Function} cb       callback
   */
  setConfig(variable, value, cb) {
    if (!cb) cb = function(){};

    let cJSON,
        cFGpath = path.join(this.projectPath, '/config/configuration.json');

    try {
      cJSON = JSON.parse(readFileSync(cFGpath));
    } catch(e) {
      if (e.code == 'ENOENT') {
        writeFileSync(cFGpath, '{}');
        cJSON = {};
      } else {
        return cb(e);
      }
    }

    if (value == 'true') value = true;
    if (value == 'false') value = false;

    _.set(cJSON, variable, value);

    writeFile(cFGpath, JSON.stringify(cJSON, null, 2), cb);
  },

  /**
   * Unset config in config/configuration.json file
   *
   * @param {String}   variable path to the variable
   * @param {String}   value
   * @param {Function} cb       callback
   */
  unSetConfig(variable, cb) {
    let cJSON,
        cFGpath = path.join(this.projectPath, '/config/configuration.json');

    try {
      cJSON = JSON.parse(readFileSync(cFGpath));
    } catch(e) {
      if (e.code == 'ENOENT') {
        writeFileSync(cFGpath, '{}');
        cJSON = {};
      } else {
        return cb(e);
      }
    }

    _.unset(cJSON, variable);

    writeFile(cFGpath, JSON.stringify(cJSON, null, 2), cb);
  },
  // set bootstrap functions
  bootstrapFunctions: require('./bootstrapFunctions'),
  // flag to check if this we.js instance did the bootstrap
  bootstrapStarted: false,
  // flag to check if needs restart
  needsRestart: false,
  // we.utils.async, we.utils._ ... see the ./utils file
  utils: require('./utils'),
  // load we.js responses
  responses: require('./responses'),
  // save we-core path to plugin.js for update e install process
  weCorePluginfile: path.resolve(__dirname, '../') + '/plugin.js',
  //Overide default toString and inspect to custom infos in we.js object
  inspect() {
    return '\nWe.js ;)\n';
  },
  toString() {
    return this.inspect();
  },
  // client side config generator
  getAppBootstrapConfig: require('./staticConfig/getAppBootstrapConfig.js'),

  /**
   * Bootstrap and initialize the app
   *
   * @param  {Object}   configOnRun optional
   * @param  {Function} cb          callback to run after load we.js
   */
  bootstrap(configOnRun, cb) {
    const we = this;
    // only bootstrap we.js one time
    if (we.bootstrapStarted) throw new Error('We.js already did bootstrap');

    we.bootstrapStarted = true;
    // configsOnRun object is optional
    if (!cb) {
      cb = configOnRun;
      configOnRun = null;
    }
    // configs on run extends default and file configs
    if (configOnRun) _.merge(we.config, configOnRun);

    // run the bootstrap hook
    we.hooks.trigger('bootstrap', we, function bootstrapDone (err) {
      if (err) {
        console.log('Error on bootstrap: ');
        throw err;
      }

      we.events.emit('we:bootstrap:done', we);

      we.log.debug('We.js bootstrap done');
      // set pm2 gracefullReload:
      we.setPM2grShutdownFN(we);

      return cb(null, we);
    });
  },

  /**
   * Start we.js server (express)
   * use after we.bootstrap
   *
   * @param  {Function} cb    callback how returns with cb(err);
   */
  startServer(cb) {
    if (!cb) cb = function(){}; // cb is optional

    let we = this;

    we.hooks.trigger('we:server:before:start' ,we ,function afterRunBeforeServerStart (err) {
      if (err) return cb(err);
      /**
       * Get port from environment and store in Express.
       */
      let port = normalizePort(we.config.port);
      we.express.set('port', port);

      /**
       * Create HTTP server with suport to url alias rewrite
       */
      const server = http.createServer(function onCreateServer (req, res){
        req.we = we;

        // suport for we.js widget API
        // install we-plugin-widget to enable this feature
        if (req.headers && req.headers['we-widget-action'] && req.method == 'POST') {
          req.isWidgetAction = true;
          req.originalMethod = req.method;
          req.method = 'GET'; // widgets only are associated to get routes
        }

        // parse extension if not is public folder
        if (!we.router.isPublicFolder(req.url)) {
          req.extension = we.router.splitExtensionFromURL(req.url);

          if (req.extension) {
            let format = we.utils.mime.getType(req.extension);

            if (req.we.config.responseTypes.includes(format)) {
              // update the header response format with extension format
              req.headers.accept = format;
              // update the old url
              req.url = req.url.replace('.'+req.extension, '');
            }
          }
        }
        // install we-plugin-url-alias to enable alias feature
        if (we.plugins['we-plugin-url-alias'] && we.config.enableUrlAlias) {
          we.router.alias.httpHandler.bind(this)(req, res);
        } else {
          we.express.bind(this)(req, res);
        }
      });

      we.events.emit('we:server:after:create', { we: we, server: server });

      /**
       * Listen on provided port, on all network interfaces.
       */

      // catch 404 and forward to error handler
      we.express.use(function routeNotFound (req, res) {
        we.log.debug('Route not found:', req.path);
        // var err = new Error('Not Found');
        // err.status = 404;
        return res.notFound();
      });

      server.listen(port);
      server.on('error', onError);
      server.on('listening', onListening);
      /**
       * Normalize a port into a number, string, or false.
       */
      function normalizePort (val) {
        let port = parseInt(val, 10);

        if (isNaN(port)) {
          // named pipe
          return val;
        }

        if (port >= 0) {
          // port number
          return port;
        }

        return false;
      }

      /**
       * Event listener for HTTP server "error" event.
       */
      function onError (error) {
        if (error.syscall !== 'listen') {
          throw error;
        }

        let bind = typeof port === 'string'
          ? 'Pipe ' + port
          : 'Port ' + port;

        // handle specific listen errors with friendly messages
        switch (error.code) {
          case 'EACCES':
            console.error(bind + ' requires elevated privileges');
            process.exit(1);
            break;
          case 'EADDRINUSE':
            console.error(bind + ' is already in use');
            process.exit(1);
            break;
          default:
            throw error;
        }
      }
      /**
       * Event listener for HTTP server "listening" event.
       */
      function onListening () {
        let addr = server.address(),
            bind = typeof addr === 'string'
          ? 'pipe ' + addr
          : 'port ' + addr.port;
        we.log.info('Run in '+we.env+' enviroment and listening on ' + bind);

        if (process.send) {
          process.send('ready');
        }
      }
      // save the current http server
      we.http = server;

      // express error handlers
      // will print stacktrace
      we.express.use(function onExpressError (err, req, res, next) {
        we.log.error('onExpressError:Error on:', req.path, err);
        res.serverError(err);
      });

      we.hooks.trigger('we:server:after:start',we, function afterHookAfterStart (err) {
        cb(err, we);
      });
    });
  },

  /**
   * Bootstrap and Start we.js server
   *
   * @param  {Object}   cfgs configs (optional)
   * @param  {Function} cb   callback
   */
  go(cfgs, cb) {
    if (!cb) {
      cb = cfgs;
      cfgs = {};
    }

    this.bootstrap(cfgs, function afterBootstrapOnWeGo (err, we) {
      if (err) throw err;
      we.startServer(cb);
    });
  },

  /**
   * Turn off process function
   *
   * @param  {Function} cb callback
   */
  exit(cb) {
    this.isExiting = true;
    // close db connection
    if (this.db.defaultConnection) {
      this.db.defaultConnection.close();
    }
    // close all loggers and wait for end writes
    this.log.closeAllLoggersAndDisconnect(this, cb);
  },

  /**
   * Helper function to delete (unpoint) pointers from response for help GC
   */
  freeResponseMemory(req, res) {
    delete res.locals.req;
    delete res.locals.regions;
    delete res.locals.Model;
    delete res.locals.body;
    delete res.locals.layoutHtml;
  },

  /**
   * Run all plugin and project cron tasks
   *
   * @param  {Function} cb callback
   */
  runCron(cb) {
    this.cron = require('./cron');
    this.cron.loadAndRunAllTasks(this, cb);
  },

  /**
   * set pm2 gracefullReload
   */
  setPM2grShutdownFN(we) {
    // old/windows version:
    process.on('message', (msg)=> {
      if (msg === 'shutdown') {
        // disconect, and exit
        we.exit( (err)=> { process.exit(err ? 1 : 0); });
      }
    });
    // new version:
    process.on('SIGINT', ()=> {
      we.exit( (err)=> { process.exit(err ? 1 : 0); });
    });
  }
};

module.exports = We;<|endoftext|>


<commit_before>/* eslint-disable no-unused-vars */

import postcss from 'postcss'
import mkdirp from 'mkdirp'
import path from 'path'
import fs from 'fs'

import nesting from 'postcss-nesting'

const getRootAtRule = atRule => {
  return (atRule.parent && atRule.parent.type === 'atrule') ? getRootAtRule(atRule.parent) : atRule
}

const hasAtRuleInside = (rule, atRuleName) => {
  let hasAtRule = false
  rule.walkAtRules(atRuleName, () => {
    hasAtRule = true
  })
  return hasAtRule
}

export default postcss.plugin('postcss-extract', (options = {}) => {
  const instance = postcss()

  // atRules = Object where key is atRule and value is path where save file
  const atRules = options.extract

  // do nothing if no extract
  if (!atRules) return instance

  // bubble atRules
  instance.use(nesting({ bubble: Object.keys(atRules) }))

  const plugin = (css, result) => {
    Object.keys(atRules).forEach(atRuleToExract => {
      const extracted = postcss.root()
      css.walkAtRules(atRuleToExract, rule => {
        extracted.append(getRootAtRule(rule))
        rule.remove()
      })

      // clean all rules except rules inside at-rule to extract
      extracted.walkRules(rule => {
        if (rule.parent.name === atRuleToExract) return
        rule.remove()
      })

      extracted.walkAtRules(rule => {
        if (rule.name === atRuleToExract) {
          // remove at-rule to extract wrapper
          rule.replaceWith(rule.nodes)
          return
        }
        if (!hasAtRuleInside(rule, atRuleToExract)) {
          // remove at-rules without at-rule to extract
          rule.remove()
          return
        }
      })

      const pathToDistFile = atRules[atRuleToExract]
      mkdirp(path.parse(pathToDistFile).dir, err => {
        if (err) {
          console.error(err) // eslint-disable-line no-console
          return
        }
        fs.writeFile(pathToDistFile, extracted.toResult().css, error => {
          if (error) {
            console.error(error) // eslint-disable-line no-console
          }
        })
      })
    })
  }

  return instance.use(plugin)
})
<commit_msg>use promise API to stop plugin work only after all files written<commit_after>/* eslint-disable no-unused-vars */

import postcss from 'postcss'
import mkdirp from 'mkdirp'
import path from 'path'
import fs from 'fs'

import nesting from 'postcss-nesting'

const getRootAtRule = atRule => {
  return (atRule.parent && atRule.parent.type === 'atrule') ? getRootAtRule(atRule.parent) : atRule
}

const hasAtRuleInside = (rule, atRuleName) => {
  let hasAtRule = false
  rule.walkAtRules(atRuleName, () => {
    hasAtRule = true
  })
  return hasAtRule
}

export default postcss.plugin('postcss-extract', (options = {}) => {
  const instance = postcss()

  // atRules = Object where key is atRule and value is path where save file
  const atRules = options.extract

  // do nothing if no extract
  if (!atRules) return instance

  // bubble atRules
  instance.use(nesting({ bubble: Object.keys(atRules) }))

  const plugin = (css, result) => {
    return new Promise((resolve, reject) => {
      Object.keys(atRules).forEach(atRuleToExract => {
        const extracted = postcss.root()
        css.walkAtRules(atRuleToExract, rule => {
          extracted.append(getRootAtRule(rule))
          rule.remove()
        })

        // clean all rules except rules inside at-rule to extract
        extracted.walkRules(rule => {
          if (rule.parent.name === atRuleToExract) return
          rule.remove()
        })

        extracted.walkAtRules(rule => {
          if (rule.name === atRuleToExract) {
            // remove at-rule to extract wrapper
            rule.replaceWith(rule.nodes)
            return
          }
          if (!hasAtRuleInside(rule, atRuleToExract)) {
            // remove at-rules without at-rule to extract
            rule.remove()
            return
          }
        })

        const pathToDistFile = atRules[atRuleToExract]
        mkdirp(path.parse(pathToDistFile).dir, err => {
          if (err) {
            reject(err)
            return
          }
          fs.writeFile(pathToDistFile, extracted.toResult().css, error => {
            if (error) {
              reject(error)
            }
            resolve()
          })
        })
      })
    })
  }

  return instance.use(plugin)
})
<|endoftext|>


<commit_before>/**
 * react-native-swiper
 * @author leecade<leecade@163.com>
 */
import React from 'react'
import ReactNative, {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Dimensions,
  TouchableOpacity,
  ViewPagerAndroid,
  Platform
} from 'react-native'

// Using bare setTimeout, setInterval, setImmediate
// and requestAnimationFrame calls is very dangerous
// because if you forget to cancel the request before
// the component is unmounted, you risk the callback
// throwing an exception.
import TimerMixin from 'react-timer-mixin'

let { width, height } = Dimensions.get('window')

/**
 * Default styles
 * @type {StyleSheetPropType}
 */
let styles = StyleSheet.create({
  container: {
    backgroundColor: 'transparent',
    position: 'relative',
  },

  wrapper: {
    backgroundColor: 'transparent',
  },

  slide: {
    backgroundColor: 'transparent',
  },

  pagination_x: {
    position: 'absolute',
    bottom: 25,
    left: 0,
    right: 0,
    flexDirection: 'row',
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor:'transparent',
  },

  pagination_y: {
    position: 'absolute',
    right: 15,
    top: 0,
    bottom: 0,
    flexDirection: 'column',
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor:'transparent',
  },

  title: {
    height: 30,
    justifyContent: 'center',
    position: 'absolute',
    paddingLeft: 10,
    bottom: -30,
    left: 0,
    flexWrap: 'nowrap',
    width: 250,
    backgroundColor: 'transparent',
  },

  buttonWrapper: {
    backgroundColor: 'transparent',
    flexDirection: 'row',
    position: 'absolute',
    top: 0,
    left: 0,
    flex: 1,
    paddingHorizontal: 10,
    paddingVertical: 10,
    justifyContent: 'space-between',
    alignItems: 'center'
  },

  buttonText: {
    fontSize: 50,
    color: '#007aff',
    fontFamily: 'Arial',
  },
})

// missing `module.exports = exports['default'];` with babel6
// export default React.createClass({
module.exports = React.createClass({

  /**
   * Props Validation
   * @type {Object}
   */
  propTypes: {
    horizontal                       : React.PropTypes.bool,
    children                         : React.PropTypes.node.isRequired,
    style                            : View.propTypes.style,
    pagingEnabled                    : React.PropTypes.bool,
    showsHorizontalScrollIndicator   : React.PropTypes.bool,
    showsVerticalScrollIndicator     : React.PropTypes.bool,
    bounces                          : React.PropTypes.bool,
    scrollsToTop                     : React.PropTypes.bool,
    removeClippedSubviews            : React.PropTypes.bool,
    automaticallyAdjustContentInsets : React.PropTypes.bool,
    showsPagination                  : React.PropTypes.bool,
    showsButtons                     : React.PropTypes.bool,
    loop                             : React.PropTypes.bool,
    autoplay                         : React.PropTypes.bool,
    autoplayTimeout                  : React.PropTypes.number,
    autoplayDirection                : React.PropTypes.bool,
    index                            : React.PropTypes.number,
    renderPagination                 : React.PropTypes.func,
  },

  mixins: [TimerMixin],

  /**
   * Default props
   * @return {object} props
   * @see http://facebook.github.io/react-native/docs/scrollview.html
   */
  getDefaultProps() {
    return {
      horizontal                       : true,
      pagingEnabled                    : true,
      showsHorizontalScrollIndicator   : false,
      showsVerticalScrollIndicator     : false,
      bounces                          : false,
      scrollsToTop                     : false,
      removeClippedSubviews            : true,
      automaticallyAdjustContentInsets : false,
      showsPagination                  : true,
      showsButtons                     : false,
      loop                             : true,
      autoplay                         : false,
      autoplayTimeout                  : 2.5,
      autoplayDirection                : true,
      index                            : 0,
    }
  },

  /**
   * Init states
   * @return {object} states
   */
  getInitialState() {
    return this.initState(this.props)
  },

  /**
   * autoplay timer
   * @type {null}
   */
  autoplayTimer: null,

  componentWillMount() {
    this.props = this.injectState(this.props)
  },

  componentWillReceiveProps(props) {
    this.setState(this.initState(props))
  },

  componentDidMount() {
    this.autoplay()
  },

  initState(props) {
    // set the current state
    const state = this.state || {}

    let initState = {
      isScrolling: false,
      autoplayEnd: false,
    }

    initState.total = props.children ? props.children.length || 1 : 0

    if (state.total === initState.total) {
      // retain the index
      initState.index = state.index
    } else {
      // reset the index
      initState.index = initState.total > 1 ? Math.min(props.index, initState.total - 1) : 0
    }

    // Default: horizontal
    initState.dir = props.horizontal === false ? 'y' : 'x'
    initState.width = props.width || width
    initState.height = props.height || height
    initState.offset = {}

    if (initState.total > 1) {
      var setup = initState.index
      if ( props.loop ) {
        setup++
      }
      initState.offset[initState.dir] = initState.dir === 'y'
        ? initState.height * setup
        : initState.width * setup
    }
    return initState
  },

  /**
   * Automatic rolling
   */
  autoplay() {
    if(
      !Array.isArray(this.props.children)
      || !this.props.autoplay
      || this.state.isScrolling
      || this.state.autoplayEnd
    ) {
      return
    }

    clearTimeout(this.autoplayTimer)

    this.autoplayTimer = this.setTimeout(() => {
      if(
        !this.props.loop && (
          this.props.autoplayDirection
            ? this.state.index === this.state.total - 1
            : this.state.index === 0
        )
      ) {
        return this.setState({ autoplayEnd: true })
      }

      this.scrollBy(this.props.autoplayDirection ? 1 : -1)
    }, this.props.autoplayTimeout * 1000)
  },

  /**
   * Scroll begin handle
   * @param  {object} e native event
   */
  onScrollBegin(e) {
    // update scroll state
    this.setState({ isScrolling: true })

    this.setTimeout(() => {
      this.props.onScrollBeginDrag && this.props.onScrollBeginDrag(e, this.state, this)
    })
  },

  /**
   * Scroll end handle
   * @param  {object} e native event
   */
  onScrollEnd(e) {
    // update scroll state
    this.setState({
      isScrolling: false
    })

    // making our events coming from android compatible to updateIndex logic
    if (!e.nativeEvent.contentOffset) {
      if (this.state.dir === 'x') {
        e.nativeEvent.contentOffset = {x: e.nativeEvent.position * this.state.width}
      } else {
        e.nativeEvent.contentOffset = {y: e.nativeEvent.position * this.state.height}
      }
    }

    this.updateIndex(e.nativeEvent.contentOffset, this.state.dir)

    // Note: `this.setState` is async, so I call the `onMomentumScrollEnd`
    // in setTimeout to ensure synchronous update `index`
    this.setTimeout(() => {
      this.autoplay()

      // if `onMomentumScrollEnd` registered will be called here
      this.props.onMomentumScrollEnd && this.props.onMomentumScrollEnd(e, this.state, this)
    })
  },

  /**
   * Update index after scroll
   * @param  {object} offset content offset
   * @param  {string} dir    'x' || 'y'
   */
  updateIndex(offset, dir) {

    let state = this.state
    let index = state.index
    let diff = offset[dir] - state.offset[dir]
    let step = dir === 'x' ? state.width : state.height

    // Do nothing if offset no change.
    if(!diff) return

    // Note: if touch very very quickly and continuous,
    // the variation of `index` more than 1.
    // parseInt() ensures it's always an integer
    index = parseInt(index + diff / step)

    if(this.props.loop) {
      if(index <= -1) {
        index = state.total - 1
        offset[dir] = step * state.total
      }
      else if(index >= state.total) {
        index = 0
        offset[dir] = step
      }
    }

    this.setState({
      index: index,
      offset: offset,
    })
  },

  /**
   * Scroll by index
   * @param  {number} index offset index
   */
  scrollBy(index) {
    if (this.state.isScrolling || this.state.total < 2) return
    let state = this.state
    let diff = (this.props.loop ? 1 : 0) + index + this.state.index
    let x = 0
    let y = 0
    if(state.dir === 'x') x = diff * state.width
    if(state.dir === 'y') y = diff * state.height

    if (Platform.OS === 'android') {
      this.refs.scrollView && this.refs.scrollView.setPage(diff)
    } else {
      this.refs.scrollView && this.refs.scrollView.scrollTo({
        y: y,
        x: x
      })
    }

    // update scroll state
    this.setState({
      isScrolling: true,
      autoplayEnd: false,
    })

    // trigger onScrollEnd manually in android
    if (Platform.OS === 'android') {
      this.setTimeout(() => {
        this.onScrollEnd({
          nativeEvent: {
            position: diff,
          }
        });
      }, 50);
    }

  },

  /**
   * Render pagination
   * @return {object} react-dom
   */
  renderPagination() {

    // By default, dots only show when `total` > 2
    if(this.state.total <= 1) return null

    let dots = []
    let ActiveDot = this.props.activeDot || <View style={{
            backgroundColor: '#007aff',
            width: 8,
            height: 8,
            borderRadius: 4,
            marginLeft: 3,
            marginRight: 3,
            marginTop: 3,
            marginBottom: 3,
          }} />;
    let Dot = this.props.dot || <View style={{
            backgroundColor:'rgba(0,0,0,.2)',
            width: 8,
            height: 8,
            borderRadius: 4,
            marginLeft: 3,
            marginRight: 3,
            marginTop: 3,
            marginBottom: 3,
          }} />;
    for(let i = 0; i < this.state.total; i++) {
      dots.push(i === this.state.index
        ?
        React.cloneElement(ActiveDot, {key: i})
        :
        React.cloneElement(Dot, {key: i})
      )
    }

    return (
      <View pointerEvents='none' style={[styles['pagination_' + this.state.dir], this.props.paginationStyle]}>
        {dots}
      </View>
    )
  },

  renderTitle() {
    let child = this.props.children[this.state.index]
    let title = child && child.props.title
    return title
      ? (
        <View style={styles.title}>
          {this.props.children[this.state.index].props.title}
        </View>
      )
      : null
  },

  renderNextButton() {
    let button;

    if (this.props.loop || this.state.index != this.state.total - 1) {
      button = this.props.nextButton || <Text style={styles.buttonText}>›</Text>
    }

    return (
      <TouchableOpacity onPress={() => button !== null && this.scrollBy.call(this, 1)}>
        <View>
          {button}
        </View>
      </TouchableOpacity>
    )
  },

  renderPrevButton() {
    let button = null

    if (this.props.loop || this.state.index != 0) {
       button = this.props.prevButton || <Text style={styles.buttonText}>‹</Text>
    }

    return (
      <TouchableOpacity onPress={() => button !== null && this.scrollBy.call(this, -1)}>
        <View>
          {button}
        </View>
      </TouchableOpacity>
    )
  },

  renderButtons() {
    return (
      <View pointerEvents='box-none' style={[styles.buttonWrapper, {width: this.state.width, height: this.state.height}, this.props.buttonWrapperStyle]}>
        {this.renderPrevButton()}
        {this.renderNextButton()}
      </View>
    )
  },
  renderScrollView(pages) {
     if (Platform.OS === 'ios')
         return (
            <ScrollView ref="scrollView"
             {...this.props}
                       contentContainerStyle={[styles.wrapper, this.props.style]}
                       contentOffset={this.state.offset}
                       onScrollBeginDrag={this.onScrollBegin}
                       onScrollEndDrag={()=>this.setState({isScrolling:false})}
                       onMomentumScrollEnd={this.onScrollEnd}>
             {pages}
            </ScrollView>
         );
      return (
         <ViewPagerAndroid ref="scrollView"
          {...this.props}
            initialPage={this.props.loop ? this.state.index + 1 : this.state.index}
            onPageSelected={this.onScrollEnd}
            style={{flex: 1}}>
            {pages}
         </ViewPagerAndroid>
      );
  },
  /**
   * Inject state to ScrollResponder
   * @param  {object} props origin props
   * @return {object} props injected props
   */
  injectState(props) {
/*    const scrollResponders = [
      'onMomentumScrollBegin',
      'onTouchStartCapture',
      'onTouchStart',
      'onTouchEnd',
      'onResponderRelease',
    ]*/

    for(let prop in props) {
      // if(~scrollResponders.indexOf(prop)
      if(typeof props[prop] === 'function'
        && prop !== 'onMomentumScrollEnd'
        && prop !== 'renderPagination'
        && prop !== 'onScrollBeginDrag'
      ) {
        let originResponder = props[prop]
        props[prop] = (e) => originResponder(e, this.state, this)
      }
    }

    return props
  },

  /**
   * Default render
   * @return {object} react-dom
   */
  render() {
    let state = this.state
    let props = this.props
    let children = props.children
    let index = state.index
    let total = state.total
    let loop = props.loop
    let dir = state.dir
    let key = 0

    let pages = []
    let pageStyle = [{width: state.width, height: state.height}, styles.slide]

    // For make infinite at least total > 1
    if(total > 1) {

      // Re-design a loop model for avoid img flickering
      pages = Object.keys(children)
      if(loop) {
        pages.unshift(total - 1)
        pages.push(0)
      }

      pages = pages.map((page, i) =>
        <View style={pageStyle} key={i}>{children[page]}</View>
      )
    }
    else pages = <View style={pageStyle}>{children}</View>

    return (
      <View style={[styles.container, {
        width: state.width,
        height: state.height
      }]}>
        {this.renderScrollView(pages)}
        {props.showsPagination && (props.renderPagination
          ? this.props.renderPagination(state.index, state.total, this)
          : this.renderPagination())}
        {this.renderTitle()}
        {this.props.showsButtons && this.renderButtons()}
      </View>
    )
  }
})
<commit_msg>Don't attempt to mutate this.props (fixes #77)<commit_after>/**
 * react-native-swiper
 * @author leecade<leecade@163.com>
 */
import React from 'react'
import ReactNative, {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Dimensions,
  TouchableOpacity,
  ViewPagerAndroid,
  Platform
} from 'react-native'

// Using bare setTimeout, setInterval, setImmediate
// and requestAnimationFrame calls is very dangerous
// because if you forget to cancel the request before
// the component is unmounted, you risk the callback
// throwing an exception.
import TimerMixin from 'react-timer-mixin'

let { width, height } = Dimensions.get('window')

/**
 * Default styles
 * @type {StyleSheetPropType}
 */
let styles = StyleSheet.create({
  container: {
    backgroundColor: 'transparent',
    position: 'relative',
  },

  wrapper: {
    backgroundColor: 'transparent',
  },

  slide: {
    backgroundColor: 'transparent',
  },

  pagination_x: {
    position: 'absolute',
    bottom: 25,
    left: 0,
    right: 0,
    flexDirection: 'row',
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor:'transparent',
  },

  pagination_y: {
    position: 'absolute',
    right: 15,
    top: 0,
    bottom: 0,
    flexDirection: 'column',
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor:'transparent',
  },

  title: {
    height: 30,
    justifyContent: 'center',
    position: 'absolute',
    paddingLeft: 10,
    bottom: -30,
    left: 0,
    flexWrap: 'nowrap',
    width: 250,
    backgroundColor: 'transparent',
  },

  buttonWrapper: {
    backgroundColor: 'transparent',
    flexDirection: 'row',
    position: 'absolute',
    top: 0,
    left: 0,
    flex: 1,
    paddingHorizontal: 10,
    paddingVertical: 10,
    justifyContent: 'space-between',
    alignItems: 'center'
  },

  buttonText: {
    fontSize: 50,
    color: '#007aff',
    fontFamily: 'Arial',
  },
})

// missing `module.exports = exports['default'];` with babel6
// export default React.createClass({
module.exports = React.createClass({

  /**
   * Props Validation
   * @type {Object}
   */
  propTypes: {
    horizontal                       : React.PropTypes.bool,
    children                         : React.PropTypes.node.isRequired,
    style                            : View.propTypes.style,
    pagingEnabled                    : React.PropTypes.bool,
    showsHorizontalScrollIndicator   : React.PropTypes.bool,
    showsVerticalScrollIndicator     : React.PropTypes.bool,
    bounces                          : React.PropTypes.bool,
    scrollsToTop                     : React.PropTypes.bool,
    removeClippedSubviews            : React.PropTypes.bool,
    automaticallyAdjustContentInsets : React.PropTypes.bool,
    showsPagination                  : React.PropTypes.bool,
    showsButtons                     : React.PropTypes.bool,
    loop                             : React.PropTypes.bool,
    autoplay                         : React.PropTypes.bool,
    autoplayTimeout                  : React.PropTypes.number,
    autoplayDirection                : React.PropTypes.bool,
    index                            : React.PropTypes.number,
    renderPagination                 : React.PropTypes.func,
  },

  mixins: [TimerMixin],

  /**
   * Default props
   * @return {object} props
   * @see http://facebook.github.io/react-native/docs/scrollview.html
   */
  getDefaultProps() {
    return {
      horizontal                       : true,
      pagingEnabled                    : true,
      showsHorizontalScrollIndicator   : false,
      showsVerticalScrollIndicator     : false,
      bounces                          : false,
      scrollsToTop                     : false,
      removeClippedSubviews            : true,
      automaticallyAdjustContentInsets : false,
      showsPagination                  : true,
      showsButtons                     : false,
      loop                             : true,
      autoplay                         : false,
      autoplayTimeout                  : 2.5,
      autoplayDirection                : true,
      index                            : 0,
    }
  },

  /**
   * Init states
   * @return {object} states
   */
  getInitialState() {
    return this.initState(this.props)
  },

  /**
   * autoplay timer
   * @type {null}
   */
  autoplayTimer: null,

  componentWillReceiveProps(props) {
    this.setState(this.initState(props))
  },

  componentDidMount() {
    this.autoplay()
  },

  initState(props) {
    // set the current state
    const state = this.state || {}

    let initState = {
      isScrolling: false,
      autoplayEnd: false,
    }

    initState.total = props.children ? props.children.length || 1 : 0

    if (state.total === initState.total) {
      // retain the index
      initState.index = state.index
    } else {
      // reset the index
      initState.index = initState.total > 1 ? Math.min(props.index, initState.total - 1) : 0
    }

    // Default: horizontal
    initState.dir = props.horizontal === false ? 'y' : 'x'
    initState.width = props.width || width
    initState.height = props.height || height
    initState.offset = {}

    if (initState.total > 1) {
      var setup = initState.index
      if ( props.loop ) {
        setup++
      }
      initState.offset[initState.dir] = initState.dir === 'y'
        ? initState.height * setup
        : initState.width * setup
    }
    return initState
  },

  /**
   * Automatic rolling
   */
  autoplay() {
    if(
      !Array.isArray(this.props.children)
      || !this.props.autoplay
      || this.state.isScrolling
      || this.state.autoplayEnd
    ) {
      return
    }

    clearTimeout(this.autoplayTimer)

    this.autoplayTimer = this.setTimeout(() => {
      if(
        !this.props.loop && (
          this.props.autoplayDirection
            ? this.state.index === this.state.total - 1
            : this.state.index === 0
        )
      ) {
        return this.setState({ autoplayEnd: true })
      }

      this.scrollBy(this.props.autoplayDirection ? 1 : -1)
    }, this.props.autoplayTimeout * 1000)
  },

  /**
   * Scroll begin handle
   * @param  {object} e native event
   */
  onScrollBegin(e) {
    // update scroll state
    this.setState({ isScrolling: true })

    this.setTimeout(() => {
      this.props.onScrollBeginDrag && this.props.onScrollBeginDrag(e, this.state, this)
    })
  },

  /**
   * Scroll end handle
   * @param  {object} e native event
   */
  onScrollEnd(e) {
    // update scroll state
    this.setState({
      isScrolling: false
    })

    // making our events coming from android compatible to updateIndex logic
    if (!e.nativeEvent.contentOffset) {
      if (this.state.dir === 'x') {
        e.nativeEvent.contentOffset = {x: e.nativeEvent.position * this.state.width}
      } else {
        e.nativeEvent.contentOffset = {y: e.nativeEvent.position * this.state.height}
      }
    }

    this.updateIndex(e.nativeEvent.contentOffset, this.state.dir)

    // Note: `this.setState` is async, so I call the `onMomentumScrollEnd`
    // in setTimeout to ensure synchronous update `index`
    this.setTimeout(() => {
      this.autoplay()

      // if `onMomentumScrollEnd` registered will be called here
      this.props.onMomentumScrollEnd && this.props.onMomentumScrollEnd(e, this.state, this)
    })
  },

  /**
   * Update index after scroll
   * @param  {object} offset content offset
   * @param  {string} dir    'x' || 'y'
   */
  updateIndex(offset, dir) {

    let state = this.state
    let index = state.index
    let diff = offset[dir] - state.offset[dir]
    let step = dir === 'x' ? state.width : state.height

    // Do nothing if offset no change.
    if(!diff) return

    // Note: if touch very very quickly and continuous,
    // the variation of `index` more than 1.
    // parseInt() ensures it's always an integer
    index = parseInt(index + diff / step)

    if(this.props.loop) {
      if(index <= -1) {
        index = state.total - 1
        offset[dir] = step * state.total
      }
      else if(index >= state.total) {
        index = 0
        offset[dir] = step
      }
    }

    this.setState({
      index: index,
      offset: offset,
    })
  },

  /**
   * Scroll by index
   * @param  {number} index offset index
   */
  scrollBy(index) {
    if (this.state.isScrolling || this.state.total < 2) return
    let state = this.state
    let diff = (this.props.loop ? 1 : 0) + index + this.state.index
    let x = 0
    let y = 0
    if(state.dir === 'x') x = diff * state.width
    if(state.dir === 'y') y = diff * state.height

    if (Platform.OS === 'android') {
      this.refs.scrollView && this.refs.scrollView.setPage(diff)
    } else {
      this.refs.scrollView && this.refs.scrollView.scrollTo({
        y: y,
        x: x
      })
    }

    // update scroll state
    this.setState({
      isScrolling: true,
      autoplayEnd: false,
    })

    // trigger onScrollEnd manually in android
    if (Platform.OS === 'android') {
      this.setTimeout(() => {
        this.onScrollEnd({
          nativeEvent: {
            position: diff,
          }
        });
      }, 50);
    }

  },

  scrollViewPropOverrides() {
    var props = this.props
    var overrides = {}

    /*
    const scrollResponders = [
      'onMomentumScrollBegin',
      'onTouchStartCapture',
      'onTouchStart',
      'onTouchEnd',
      'onResponderRelease',
    ]
    */

    for(let prop in props) {
      // if(~scrollResponders.indexOf(prop)
      if(typeof props[prop] === 'function'
        && prop !== 'onMomentumScrollEnd'
        && prop !== 'renderPagination'
        && prop !== 'onScrollBeginDrag'
      ) {
        let originResponder = props[prop]
        overrides[prop] = (e) => originResponder(e, this.state, this)
      }
    }

    return overrides
  },

  /**
   * Render pagination
   * @return {object} react-dom
   */
  renderPagination() {

    // By default, dots only show when `total` > 2
    if(this.state.total <= 1) return null

    let dots = []
    let ActiveDot = this.props.activeDot || <View style={{
            backgroundColor: '#007aff',
            width: 8,
            height: 8,
            borderRadius: 4,
            marginLeft: 3,
            marginRight: 3,
            marginTop: 3,
            marginBottom: 3,
          }} />;
    let Dot = this.props.dot || <View style={{
            backgroundColor:'rgba(0,0,0,.2)',
            width: 8,
            height: 8,
            borderRadius: 4,
            marginLeft: 3,
            marginRight: 3,
            marginTop: 3,
            marginBottom: 3,
          }} />;
    for(let i = 0; i < this.state.total; i++) {
      dots.push(i === this.state.index
        ?
        React.cloneElement(ActiveDot, {key: i})
        :
        React.cloneElement(Dot, {key: i})
      )
    }

    return (
      <View pointerEvents='none' style={[styles['pagination_' + this.state.dir], this.props.paginationStyle]}>
        {dots}
      </View>
    )
  },

  renderTitle() {
    let child = this.props.children[this.state.index]
    let title = child && child.props.title
    return title
      ? (
        <View style={styles.title}>
          {this.props.children[this.state.index].props.title}
        </View>
      )
      : null
  },

  renderNextButton() {
    let button;

    if (this.props.loop || this.state.index != this.state.total - 1) {
      button = this.props.nextButton || <Text style={styles.buttonText}>›</Text>
    }

    return (
      <TouchableOpacity onPress={() => button !== null && this.scrollBy.call(this, 1)}>
        <View>
          {button}
        </View>
      </TouchableOpacity>
    )
  },

  renderPrevButton() {
    let button = null

    if (this.props.loop || this.state.index != 0) {
       button = this.props.prevButton || <Text style={styles.buttonText}>‹</Text>
    }

    return (
      <TouchableOpacity onPress={() => button !== null && this.scrollBy.call(this, -1)}>
        <View>
          {button}
        </View>
      </TouchableOpacity>
    )
  },

  renderButtons() {
    return (
      <View pointerEvents='box-none' style={[styles.buttonWrapper, {width: this.state.width, height: this.state.height}, this.props.buttonWrapperStyle]}>
        {this.renderPrevButton()}
        {this.renderNextButton()}
      </View>
    )
  },

  renderScrollView(pages) {
     if (Platform.OS === 'ios')
         return (
            <ScrollView ref="scrollView"
             {...this.props}
             {...this.scrollViewPropOverrides()}
                       contentContainerStyle={[styles.wrapper, this.props.style]}
                       contentOffset={this.state.offset}
                       onScrollBeginDrag={this.onScrollBegin}
                       onScrollEndDrag={()=>this.setState({isScrolling:false})}
                       onMomentumScrollEnd={this.onScrollEnd}>
             {pages}
            </ScrollView>
         );
      return (
         <ViewPagerAndroid ref="scrollView"
          {...this.props}
            initialPage={this.props.loop ? this.state.index + 1 : this.state.index}
            onPageSelected={this.onScrollEnd}
            style={{flex: 1}}>
            {pages}
         </ViewPagerAndroid>
      );
  },

  /**
   * Default render
   * @return {object} react-dom
   */
  render() {
    let state = this.state
    let props = this.props
    let children = props.children
    let index = state.index
    let total = state.total
    let loop = props.loop
    let dir = state.dir
    let key = 0

    let pages = []
    let pageStyle = [{width: state.width, height: state.height}, styles.slide]

    // For make infinite at least total > 1
    if(total > 1) {

      // Re-design a loop model for avoid img flickering
      pages = Object.keys(children)
      if(loop) {
        pages.unshift(total - 1)
        pages.push(0)
      }

      pages = pages.map((page, i) =>
        <View style={pageStyle} key={i}>{children[page]}</View>
      )
    }
    else pages = <View style={pageStyle}>{children}</View>

    return (
      <View style={[styles.container, {
        width: state.width,
        height: state.height
      }]}>
        {this.renderScrollView(pages)}
        {props.showsPagination && (props.renderPagination
          ? this.props.renderPagination(state.index, state.total, this)
          : this.renderPagination())}
        {this.renderTitle()}
        {this.props.showsButtons && this.renderButtons()}
      </View>
    )
  }
})
<|endoftext|>


<commit_before>
var through = require ('through2')
  , mjmlDefaultEngine = require ('mjml').default
  , gutil = require ('gulp-util');

var GulpError = gutil.PluginError,
			NAME = 'MJML';

module.exports = function mjml (mjmlEngine) {
  if(mjmlEngine === undefined) {
    mjmlEngine = mjmlDefaultEngine;
  }

	return through.obj(function (file, enc, callback) {

		if (file.isStream()) {
			this.emit('error', new PluginError(NAME, 'Streams are not supported!'));
			return callback()
		}

		if (file.isBuffer()) {
			var output = file.clone();
			output.contents = new Buffer(mjmlEngine.mjml2html(file.contents.toString()));
			output.path = gutil.replaceExtension(file.path.toString(), '.html');
			this.push(output);
		}
		return callback();
	})
};
<commit_msg>Fixes the use of the default engine<commit_after>
var through = require ('through2')
  , mjmlDefaultEngine = require ('mjml')
  , gutil = require ('gulp-util');

var GulpError = gutil.PluginError,
			NAME = 'MJML';

module.exports = function mjml (mjmlEngine) {
  if(mjmlEngine === undefined) {
    mjmlEngine = mjmlDefaultEngine;
  }

	return through.obj(function (file, enc, callback) {

		if (file.isStream()) {
			this.emit('error', new PluginError(NAME, 'Streams are not supported!'));
			return callback()
		}

		if (file.isBuffer()) {
			var output = file.clone();
			output.contents = new Buffer(mjmlEngine.mjml2html(file.contents.toString()));
			output.path = gutil.replaceExtension(file.path.toString(), '.html');
			this.push(output);
		}
		return callback();
	})
};
<|endoftext|>