src/callsite/wrap.coffee
328155
function(err, frame) {
  var _frame, column, line, match, origin, position, source;
  if (coffeePrepare && (match = coffeeStackRegex.exec(coffeePrepare(err, [frame])))) {
    _frame = clone(frame);
    _frame.getFileName = function() {
      return match[1] + '.coffee';
    };
    _frame.getLineNumber = function() {
      return match[2];
    };
    _frame.getColumnNumber = function() {
      return match[3] - 1;
    };
    _frame.getScriptNameOrSourceURL = function() {
      return match[1] + '.coffee';
    };
    return _frame;
  }
  source = frame.getFileName() || frame.getScriptNameOrSourceURL();
  if (source) {
    line = frame.getLineNumber();
    column = frame.getColumnNumber() - 1;
    if (line === 1 && !frame.isEval()) {
      column -= 62;
    }
    position = sourceMapSupport.mapSourcePosition({
      source: source,
      line: line,
      column: column
    });
    _frame = clone(frame);
    _frame.getFileName = function() {
      return position.source;
    };
    _frame.getLineNumber = function() {
      return position.line;
    };
    _frame.getColumnNumber = function() {
      return position.column + 1;
    };
    _frame.getScriptNameOrSourceURL = function() {
      return position.source;
    };
    return _frame;
  }
  origin = frame.isEval() && frame.getEvalOrigin();
  if (origin) {
    origin = mapEvalOrigin(origin);
    _frame = clone(frame);
    _frame.getEvalOrigin = function() {
      return origin;
    };
    return _frame;
  }
  return frame;
}
134088
function(dbg, raFn, subName, g, name, argv_, context, outerCallback, callback) {

  var argv = _.extend({}, argv_);

  g[name] = {};

  return raFn(argv, context, function(err, result_) {
    if (err) { return sg.die(err, outerCallback, 'fetching '+name); }

    var result = subName ? result_[subName] : result_;
    if (_.isArray(result)) {
      g[name] = [];
      _.each(result, function(value) {
        g[name].push(value);
      });
    } else {
      _.each(result, function(value, key) {
        g[name][key] = value;
      });
    }

    // Get from prod
    var argv2      = _.extend({}, argv_, jsaws.getAcct('pub', process.env.JSAWS_AWS_ACCT_EXTRA_CREDS), {session:'prod'});

    return raFn(argv2, context, function(err, result_) {
      if (err) { return sg.die(err, outerCallback, 'fetching '+name); }

      var result = subName ? result_[subName] : result_;
      if (_.isArray(result)) {
        _.each(result, function(value) {
          g[name].push(value);
        });
      } else {
        _.each(result, function(value, key) {
          g[name][key] = value;
        });
      }

      return callback.apply(this, arguments);
    });
  });
}
728178
function walk(wpath, type, excludeDir, callback) {
  // regex - any chars, then dash type, 's' is optional, with .js or .coffee extension, case-insensitive
  // e.g. articles-MODEL.js or mypackage-routes.coffee
  var rgx = new RegExp('(.*)-' + type + '(s?).(js|coffee)$', 'i');
  if (!fs.existsSync(wpath)) return;
  fs.readdirSync(wpath).forEach(function(file) {
    var newPath = path.join(wpath, file);
    var stat = fs.statSync(newPath);
    if (stat.isFile() && (rgx.test(file) || (baseRgx.test(file)) && ~newPath.indexOf(type))) {
      // if (!rgx.test(file)) console.log('  Consider updating filename:', newPath);
      callback(newPath);
    } else if (stat.isDirectory() && file !== excludeDir && ~newPath.indexOf(type)) {
      walk(newPath, type, excludeDir, callback);
    }
  });
}
1068710
function parser(indexFilePath, options, done) {
	gdebug('Start');

	var modules      = []
	  , deep         = 0
	  , options      = _.extend({}, defaults, options)
	  , noparse      = options.noparse || []
	  , parsers      = [];
	;

	// try to resolve index filepath :
	indexFilePath = indexResolve(indexFilePath);
	if(!indexFilePath) {
		return done(new Error('Index not found for :' + indexFilePath));
	}

	// Prepare path subsitution by resolving all paths 
	// like we resolve the index :
	options.substitute = (function() {
		var substitute   = {};
		_.each(options.substitute, function(to, from) {
			debug('substitution prepare: %s to %s', from, to)
			var _to   = indexResolve(to);
			if(!_to) {
				debug('Module subsitution error this module can not be resolved (to):' + to)
				return done(new Error('Module subsitution error this module can not be resolved (to):' + to));
			}
			var _from = indexResolve(from);
			if(!_from) {
				debug('Module subsitution error this module can not be resolved (from):' + from)
				return done(new Error('Module subsitution error this module can not be resolved (from):' + from));
			}
			debug('    substitution result: %s to %s', _from, _to)
			substitute[_from] = _to;
		})
		return substitute;
	})();

	// Prepare the parser list, option parsers before default parsers :
	_.each(options.parsers, function(def) {
		parsers.push(def);
	});
	parsers.push({match: /\.coffee$/, parse: require('./parsers/coffee')});
	parsers.push({match: /\.css$/, parse: require('./parsers/css')});
	parsers.push({match: /\.html$/, parse: require('./parsers/html')});
	parsers.push({match: /\.jade$/, parse: require('./parsers/jade')});
	parsers.push({match: /\.json$/, parse: require('./parsers/json')});
	parsers.push({match: /\.sass$/, parse: require('./parsers/sass')});
	parsers.push({match: /\.styl$/, parse: require('./parsers/stylus')});
	parsers.push({match: /\.js$/,   parse: require('./parsers/javascript')});
	parsers.push({match: /\.(txt|html)$/,   parse: require('./parsers/txt')});

	// Parse a source an return a valid
	// javascript source injectable in an nway
	// define() template.
	// This method call the first valid parser
	// defined by user (options.parsers) or in
	// the default parsers
	function parse(src, module, makeModule, options) {
		// Find the first valid parser :
		debug('Find a parser for :', module.path)
		var result = _.find(parsers, function(def) {
			// debug('    Check parser match :', def.match)
			if(def.match instanceof RegExp) {
				return def.match.test(module.path);
			} else if ('string'   == typeof def.match) {
				return minimatch(module.path, def.match);
			} else if ('function' == typeof def.match) {
				return def.match(src, module, makeModule, options);
			} else {
				return false;
			}
		});
		if(!result) {
			debug('Warning: No valid parser found for %s. Json string is exported', module.path)
			return 'module.exports = ' + JSON.stringify(src);
		} else {
			debug('Ok parser match :', result.match);
			return result.parse(src, module, makeModule, options);
		}
	}

	// Create a module object for the index
	// receives an absolute filepath to parse, and return
	// a new Module object
	function makeModule(index) {

		var stored, src, srcPath, relpath;

		// Prepare module
		var module  = new Module({
			 uid:    index
			,req:    []
			,path:   index
			,relpath: null
			,isNodeModule: false
			,isAsyncModule: arequirePath === index
			,arequirePath:  arequirePath
			,index:  index
		});

		if(~module.path.indexOf('/node_modules/')) module.isNodeModule = true;

		relpath = path.relative(process.cwd(), module.path);
		relpath = !/^\./.test(relpath) ? './' + relpath : relpath;
		module.relpath = relpath;

		debug('makeModule for %s', relpath);

		// Check for stored version of this path
		stored = _.find(modules, function(p) {
			return module.path === p.path;
		});
		if(stored) {
			debug('allready stored : return (absolute path match)');
			return stored;
		}

		// Read source
		src           = fs.readFileSync(module.path, 'utf8');
		module.mtime  = fs.statSync(module.path).mtime;
		module.uid    = getUID({src: src, path:module.path, options: options});

		// Check for stored version with same uid
		stored = _.find(modules, function(p) {
			return module.uid  === p.uid;
		});
		if(stored) {
			debug('allready stored : return (md5 hash match)');
			return stored;
		}

		// Save module
		modules.push(module);

		// Do not parse ?
		module.notparsed = _.find(noparse, function(np) {
			if(np instanceof RegExp) {
				return np.test(module.path);
			} else if ('string'   == typeof np) {
				return minimatch(module.path, np);
			} else if ('function' == typeof np) {
				return np(module.path, module);
			} else {
				return false;
			}
		});

		// Parse
		if(module.notparsed) {
			debug('  no parse');
		} else {
			debug('  run parse');
			src = parse(src, module, makeModule, options);
		}

		// Store the module source :
		module.source = src;


		// Return the module object

		debug('end %s', relpath);
		return module;
	}

	var root = makeModule(indexFilePath);

	process.nextTick(function() {

		gdebug('End');
		done(null, modules);
	})
}
535350
function wrapper(node, schema) {

    // NODES['*'] = xtend(NODES['*'], schema.NODES['*']);
    // delete schema.NODES;

    var ctx = {type: 'root', children: []}
    var replace

    if (!node || typeof node !== 'object' || !node.type) {
        return ctx
    }

    replace = one(xtend(defaults, schema || {}), node, [])

    if (!replace) {
        return ctx
    }

    if ('length' in replace) {
        if (replace.length === 1) {
            return replace[0]
        }

        ctx.children = replace

        return ctx
    }

    return replace
}
674919
function wrapQueryMethod(method) {
  Druid.prototype[method] = function(query, callback) {
    if (!this.ready) {
      var self = this
        , onready
        , onerror

      onready = function() {
        self.removeListener('error', onerror)
        self[method](query, callback)
      }

      onerror = function(err) {
        self.removeListener('ready', onready)
        callback(err)
      }

      this.once('ready', onready)
      this.once('error', onerror)

      return
    }

    var ds = query.dataSource()

    if (!this.dataSources.hasOwnProperty(ds)) {
      callback(new DruidError('No node serves data source: ' + ds))
    }
    else {
      var node = getLessLoaded(this, ds)

      node[method](query, callback)
    }
  }
}
1093503
function buildDbMigrateArgs(grunt, config, command) {
  var args = [];
  var name = grunt.option('name');

  args.push(command);

  if (command === 'create') {
    if (!name) {
      throw new Error('--name required to create migration');
    }
    args.push(name);
  }

  if (grunt.option('count') !== undefined) {
    args.push('--count');
    args.push(grunt.option('count'));
  }

  if (grunt.option('dry-run')) {
    args.push('--dry-run');
  }

  if (grunt.option('db-verbose')) {
    args.push('--verbose');
  }

  if (grunt.option('sql-file')) {
    args.push('--sql-file');
  }

  if (grunt.option('coffee-file')) {
    args.push('--coffee-file');
  } else if (config.coffeeFile) {
    args.push('--coffee-file');
  }

  if (grunt.option('migrations-dir')) {
    args.push('--migrations-dir');
    args.push(grunt.option('migrations-dir'));
  } else if (config.migrationsDir) {
    args.push('--migrations-dir');
    args.push(config.migrationsDir);
  }

  if (grunt.option('table')) {
    args.push('--table');
    args.push(grunt.option('table'));
  } else if (config.table) {
    args.push('--table');
    args.push(config.table);
  }

  return args;
}
813561
function readApi(file, fn) {
  var ext = path.extname(file);
  if ('.js' === ext || '.ts' === ext) {
    readJsDoc(file, fn);
  } else if ('.yml' === ext) {
    readYml(file, fn);
  } else if ('.coffee' === ext) {
    readCoffee(file, fn);
  } else {
    throw new Error('Unsupported extension \'' + ext + '\'');
  }
}
613203
function streamWrappers (grunt, fileData, options) {
    stream.createWriteStream(fileData.tmpWrapStart, () => {
        streamWrapperEnd(grunt, fileData, options);
    });

    if (options.license) {
        streamLicense(grunt, fileData, options);
    } else {
        streamWrapperStart(grunt, fileData, options);
    }
}
939763
function tiCalls( content, tmpl, data, options ) {
		if ( !content ) {
			return stack.pop();
		}
		stack.push({ _: content, tmpl: tmpl, item:this, data: data, options: options });
	}
473576
function() {
        var dest = gulp.dest('tmp/');
        dest.on('end', function() {
          grunt.log.ok('Created tmp/fn.js');
        });
        return gulp.src('test/fixtures/*.coffee')
          .pipe(coffee())
          .pipe(concat('fn.js'))
          .pipe(dest);
      }
906146
function wrap(callback, name) {
  var isLST
    , stack
    , d

  if ('function' !== typeof callback || callback && callback.name === '_trycatchOnError') return callback

  isLST = options['long-stack-traces']
  d = process.domain
  if (isLST) {
    stack = getStack(d)
  }

  // Inherit from callback for when properties are added
  newCallback.__proto__ = callback
  return newCallback

  function newCallback() {
    if (isLST && d) d.currentStack = stack

    runInDomain(d, callback, trycatchitApply, [this, arguments])
  }
}
84783
function(defaultModule) {
		var packages = [],
			dir = path.dirname(callsite()[1].getFileName()) + '/',
			namespace = path.basename(dir),
			target = require(dir + defaultModule || 'api/services/Service');
		
		loaded = false;

		// Analyze the package for Sails-like components
		packages.push(function(next) {
			loadPackage(target, dir, 'config', {
	            filter    : /(.+)\.(js|json|coffee|litcoffee)$/,
	            identity  : false
	          }, next);
		});
		packages.push(function(next) {
			loadPackage(target, dir, 'controllers', {
		        filter: /(.+)Controller\.(js|coffee|litcoffee)$/,
		        flattenDirectories: true,
		        keepDirectoryPath: true,
		        replaceExpr: /Controller/
		      }, next);
		});
		packages.push(function(next) {
			loadPackage(target, dir, 'policies', {
		        filter: /(.+)\.(js|coffee|litcoffee)$/,
		        replaceExpr: null,
		        flattenDirectories: true,
		        keepDirectoryPath: true
		      }, next);
		});
		packages.push(function(next) {
			loadPackage(target, dir, 'services', {
		        filter      : /(.+)\.(js|coffee|litcoffee)$/,
		        depth     : 1,
		        caseSensitive : true
		      }, next);
		});
		packages.push(function(next) {
			loadPackage(target, dir, 'adapters', {
		        filter    : /(.+Adapter)\.(js|coffee|litcoffee)$/,
		        replaceExpr : /Adapter/,
		        flattenDirectories: true
		      }, next);
		});
		packages.push(function(next) {
			loadPackage(target, dir, 'models', {
		        filter    : /^([^.]+)\.(js|coffee|litcoffee)$/,
		        replaceExpr : /^.*\//,
		        flattenDirectories: true
		      }, next);
		});
		packages.push(function(next) {
			loadPackage(target, dir, 'hooks', {
		        filter: /^(.+)\.(js|coffee|litcoffee)$/,
	
		        // Hooks should be defined as either single files as a function
		        // OR (better yet) a subfolder with an index.js file
		        // (like a standard node module)
		        depth: 2
		      }, next);
		});
		packages.push(function(next) {
			loadPackage(target, dir, 'blueprints', {
		        filter: /(.+)\.(js|coffee|litcoffee)$/,
		        useGlobalIdForKeyName: true
		      }, next);
		});
		packages.push(function(next) {
			loadPackage(target, dir, 'responses', {
		        filter: /(.+)\.(js|coffee|litcoffee)$/,
		        useGlobalIdForKeyName: true
		      }, next);
		});

		// Attach Sails-like components to the NPM package via buildDirectory
		async.series(packages);

		// Modify the table name of the model to be namespace-friendly
		_.each(target.models, function(model, index) {
			// @TODO: Reduce versioning collision by analyzing the package.json as well?

			model.originalIdentity = model.identity;
			model.originalGlobalId = model.globalId;
			model.identity = namespace + '_' + model.identity;
			model.globalId = namespace + '_' + model.globalId;

			_.each(model.attributes, function(attribute) {
				if(attribute instanceof Object) {
					_.each(attribute, function(value, property) {
						if(property == 'collection' || property == 'model') {
							attribute[property] = namespace + '_' + attribute[property];
						}
					});
				}
			});
		});

		// Modify the services to be namespace-friendly
		_.each(target.services, function(service, index) {
			service.originalIdentity = service.globalId;
			service.identity = namespace + '_' + service.identity;
			service.globalId = namespace + '_' + service.globalId;
		});

		// Register the package as loaded
		Bulkhead[dir] = target;
		Bulkhead[dir].plugin = Bulkhead[dir]; 

		return Bulkhead[dir];
	}
417416
def coffee_compile(source):
    """"""
    with open(COFFEE_COMPILER, 'rb') as coffeescript_js:
        return evaljs(
            (coffeescript_js.read().decode('utf-8'),
             'CoffeeScript.compile(dukpy.coffeecode)'),
            coffeecode=source
        )
204088
function(src, opt, callback) {
  if (Object.prototype.toString.call(src) !== '[object String]')
    throw new TypeError('First parameter must be a string.');
  src = src.trim();
  var mySplitInput = splitInput(src);

  return mySplitInput ?  {
      meta : yaml.safeLoad(mySplitInput[0]),
      html : marked(mySplitInput[1], opt, callback)
    } : {
      meta : null,
      html : marked(src, opt, callback)
    };
}
925256
function _wrapSelectedStatements (wrapperName, err) {
        var editor = EditorManager.getActiveEditor();
        if (!editor) {
            return;
        }
        initializeRefactoringSession(editor);

        var startIndex = current.startIndex,
            endIndex = current.endIndex,
            selectedText = current.selectedText,
            pos;

        if (selectedText.length === 0) {
            var statementNode = RefactoringUtils.findSurroundASTNode(current.ast, {start: startIndex}, ["Statement"]);
            if (!statementNode) {
                current.editor.displayErrorMessageAtCursor(err);
                return;
            }
            selectedText = current.text.substr(statementNode.start, statementNode.end - statementNode.start);
            startIndex = statementNode.start;
            endIndex = statementNode.end;
        } else {
            var selectionDetails = RefactoringUtils.normalizeText(selectedText, startIndex, endIndex);
            selectedText = selectionDetails.text;
            startIndex = selectionDetails.start;
            endIndex = selectionDetails.end;
        }

        if (!RefactoringUtils.checkStatement(current.ast, startIndex, endIndex, selectedText)) {
            current.editor.displayErrorMessageAtCursor(err);
            return;
        }

        pos = {
            "start": current.cm.posFromIndex(startIndex),
            "end": current.cm.posFromIndex(endIndex)
        };

        current.document.batchOperation(function() {
            current.replaceTextFromTemplate(wrapperName, {body: selectedText}, pos);
        });

        if (wrapperName === TRY_CATCH) {
            var cursorLine = current.editor.getSelection().end.line - 1,
                startCursorCh = current.document.getLine(cursorLine).indexOf("\/\/"),
                endCursorCh = current.document.getLine(cursorLine).length;

            current.editor.setSelection({"line": cursorLine, "ch": startCursorCh}, {"line": cursorLine, "ch": endCursorCh});
        } else if (wrapperName === WRAP_IN_CONDITION) {
            current.editor.setSelection({"line": pos.start.line, "ch": pos.start.ch + 4}, {"line": pos.start.line, "ch": pos.start.ch + 13});
        }
    }
1339611
function _wrapCalls(options){
            return function(){
                var api;

                options.func.apply(options.context, Array.prototype.slice.call(arguments, 0));

                for (var i = 0; i < externalAPIS.length; i++) {
                    api = externalAPIS[i];
                    if (api[options.triggerType]) {
                        try {
                            api[options.triggerType].apply(api.context,Array.prototype.slice.call(arguments, 0));
                        }
                        catch (exc) {}
                    }
                }
            };
        }