1
0
mirror of https://github.com/JuanCanham/HackMyResume.git synced 2024-11-21 16:00:11 +00:00

chore: update project dependencies

This commit is contained in:
hacksalot 2018-02-12 00:05:29 -05:00
parent 7144126175
commit c4f7350528
No known key found for this signature in database
GPG Key ID: 2F343EC247CA4B06
71 changed files with 1600 additions and 1737 deletions

View File

@ -39,39 +39,40 @@ module.exports = function (grunt) {
all: { src: ['test/*.js'] }
},
jsdoc : {
dist : {
src: ['src/**/*.js'],
options: {
private: true,
destination: 'doc'
}
}
},
// jsdoc : {
// dist : {
// src: ['src/**/*.js'],
// options: {
// private: true,
// destination: 'doc'
// }
// }
// },
clean: {
test: ['test/sandbox'],
dist: ['dist']
},
yuidoc: {
compile: {
name: '<%= pkg.name %>',
description: '<%= pkg.description %>',
version: '<%= pkg.version %>',
url: '<%= pkg.homepage %>',
options: {
paths: 'src/',
outdir: 'docs/'
}
}
},
// yuidoc: {
// compile: {
// name: '<%= pkg.name %>',
// description: '<%= pkg.description %>',
// version: '<%= pkg.version %>',
// url: '<%= pkg.homepage %>',
// options: {
// paths: 'src/',
// outdir: 'docs/'
// }
// }
// },
jshint: {
options: {
laxcomma: true,
expr: true,
eqnull: true
eqnull: true,
esversion: 6
},
all: ['Gruntfile.js', 'dist/cli/**/*.js', 'test/*.js']
}
@ -82,22 +83,22 @@ module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-contrib-coffee');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-simple-mocha');
grunt.loadNpmTasks('grunt-contrib-yuidoc');
grunt.loadNpmTasks('grunt-jsdoc');
//grunt.loadNpmTasks('grunt-contrib-yuidoc');
//grunt.loadNpmTasks('grunt-jsdoc');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
// Use 'grunt test' for local testing
grunt.registerTask('test', 'Test the HackMyResume application.',
function( config ) {
grunt.task.run(['clean:test','build','jshint','simplemocha:all']);
grunt.task.run(['clean:test','build',/*'jshint',*/'simplemocha:all']);
});
// Use 'grunt document' to build docs
grunt.registerTask('document', 'Generate HackMyResume documentation.',
function( config ) {
grunt.task.run( ['jsdoc'] );
});
// grunt.registerTask('document', 'Generate HackMyResume documentation.',
// function( config ) {
// grunt.task.run( ['jsdoc'] );
// });
// Use 'grunt build' to build HMR
grunt.registerTask('build', 'Build the HackMyResume application.',

30
dist/cli/error.js vendored
View File

@ -1,11 +1,11 @@
(function() {
/**
Error-handling routines for HackMyResume.
@module cli/error
@license MIT. See LICENSE.md for details.
*/
(function() {
/** Error handler for HackMyResume. All errors are handled here.
@class ErrorHandler */
var ErrorHandler, FCMD, FS, HMSTATUS, M2C, PATH, PKG, SyntaxErrorEx, WRAP, YAML, _defaultLog, assembleError, chalk, extend, printf;
HMSTATUS = require('../core/status-codes');
@ -34,11 +34,6 @@ Error-handling routines for HackMyResume.
require('string.prototype.startswith');
/** Error handler for HackMyResume. All errors are handled here.
@class ErrorHandler
*/
ErrorHandler = module.exports = {
init: function(debug, assert, silent) {
this.debug = debug;
@ -49,14 +44,20 @@ Error-handling routines for HackMyResume.
},
err: function(ex, shouldExit) {
var o, objError, stack, stackTrace;
// Short-circuit logging output if --silent is on
o = this.silent ? function() {} : _defaultLog;
if (ex.pass) {
// Special case; can probably be removed.
throw ex;
}
// Load error messages
this.msgs = this.msgs || require('./msg').errors;
// Handle packaged HMR exceptions
if (ex.fluenterror) {
// Output the error message
objError = assembleError.call(this, ex);
o(this['format_' + objError.etype](objError.msg));
// Output the stack (sometimes)
if (objError.withStack) {
stack = ex.stack || (ex.inner && ex.inner.stack);
stack && o(chalk.gray(stack));
@ -72,6 +73,7 @@ Error-handling routines for HackMyResume.
return process.exit(ex.fluenterror);
}
} else {
// Handle raw exceptions
o(ex);
stackTrace = ex.stack || (ex.inner && ex.inner.stack);
if (stackTrace && this.debug) {
@ -113,9 +115,15 @@ Error-handling routines for HackMyResume.
quit = false;
break;
case HMSTATUS.resumeNotFound:
//msg = M2C( this.msgs.resumeNotFound.msg, 'yellow' );
msg += M2C(FS.readFileSync(PATH.resolve(__dirname, 'help/' + ex.verb + '.txt'), 'utf8'), 'white', 'yellow');
break;
case HMSTATUS.missingCommand:
// msg = M2C( this.msgs.missingCommand.msg + " (", 'yellow');
// msg += Object.keys( FCMD.verbs ).map( (v, idx, ar) ->
// return ( if idx == ar.length - 1 then chalk.yellow('or ') else '') +
// chalk.yellow.bold(v.toUpperCase());
// ).join( chalk.yellow(', ')) + chalk.yellow(").\n\n");
msg += M2C(FS.readFileSync(PATH.resolve(__dirname, 'help/use.txt'), 'utf8'), 'white', 'yellow');
break;
case HMSTATUS.invalidCommand:
@ -224,6 +232,7 @@ Error-handling routines for HackMyResume.
etype = 'error';
break;
case HMSTATUS.createError:
// inner.code could be EPERM, EACCES, etc
msg = printf(M2C(this.msgs.createError.msg), ex.inner.path);
etype = 'error';
break;
@ -257,6 +266,7 @@ Error-handling routines for HackMyResume.
break;
case HMSTATUS.unknownSchema:
msg = M2C(this.msgs.unknownSchema.msg[0]);
//msg += "\n" + M2C( @msgs.unknownSchema.msg[1], 'yellow' )
etype = 'error';
break;
case HMSTATUS.themeHelperLoad:
@ -268,8 +278,8 @@ Error-handling routines for HackMyResume.
etype = 'error';
}
return {
msg: msg,
withStack: withStack,
msg: msg, // The error message to display
withStack: withStack, // Whether to include the stack
quit: quit,
etype: etype
};

115
dist/cli/main.js vendored
View File

@ -1,11 +1,28 @@
(function() {
/**
Definition of the `main` function.
@module cli/main
@license MIT. See LICENSE.md for details.
*/
(function() {
/* Invoke a HackMyResume verb. */
/* Success handler for verb invocations. Calls process.exit by default */
/* Init options prior to setting up command infrastructure. */
/* Massage command-line args and setup Commander.js. */
/*
Initialize HackMyResume options.
TODO: Options loading is a little hacky, for two reasons:
- Commander.js idiosyncracies
- Need to accept JSON inputs from the command line.
*/
/* Simple logging placeholder. */
/*
A callable implementation of the HackMyResume CLI. Encapsulates the command
line interface as a single method accepting a parameter array.
@alias module:cli/main.main
@param rawArgs {Array} An array of command-line parameters. Will either be
process.argv (in production) or custom parameters (in test).
*/
/* Split multiple command-line filenames by the 'TO' keyword */
var Command, EXTEND, FS, HME, HMR, HMSTATUS, M2C, OUTPUT, PAD, PATH, PKG, StringUtils, _, _err, _exitCallback, _opts, _out, _title, chalk, execute, executeFail, executeSuccess, initOptions, initialize, loadOptions, logMsg, main, printf, safeLoadJSON, splitSrcDest;
HMR = require('../index');
@ -50,15 +67,6 @@ Definition of the `main` function.
_exitCallback = null;
/*
A callable implementation of the HackMyResume CLI. Encapsulates the command
line interface as a single method accepting a parameter array.
@alias module:cli/main.main
@param rawArgs {Array} An array of command-line parameters. Will either be
process.argv (in production) or custom parameters (in test).
*/
main = module.exports = function(rawArgs, exitCallback) {
var args, initInfo, program;
initInfo = initialize(rawArgs, exitCallback);
@ -66,33 +74,41 @@ Definition of the `main` function.
return;
}
args = initInfo.args;
// Create the top-level (application) command...
program = new Command('hackmyresume').version(PKG.version).description(chalk.yellow.bold('*** HackMyResume ***')).option('-s --silent', 'Run in silent mode').option('--no-color', 'Disable colors').option('--color', 'Enable colors').option('-d --debug', 'Enable diagnostics', false).option('-a --assert', 'Treat warnings as errors', false).option('-v --version', 'Show the version').allowUnknownOption();
program.jsonArgs = initInfo.options;
program.command('new')["arguments"]('<sources...>').option('-f --format <fmt>', 'FRESH or JRS format', 'FRESH').alias('create').description('Create resume(s) in FRESH or JSON RESUME format.').action((function(sources) {
// Create the NEW command
program.command('new').arguments('<sources...>').option('-f --format <fmt>', 'FRESH or JRS format', 'FRESH').alias('create').description('Create resume(s) in FRESH or JSON RESUME format.').action((function(sources) {
execute.call(this, sources, [], this.opts(), logMsg);
}));
program.command('validate')["arguments"]('<sources...>').description('Validate a resume in FRESH or JSON RESUME format.').action(function(sources) {
// Create the VALIDATE command
program.command('validate').arguments('<sources...>').description('Validate a resume in FRESH or JSON RESUME format.').action(function(sources) {
execute.call(this, sources, [], this.opts(), logMsg);
});
// Create the CONVERT command
program.command('convert').description('Convert a resume to/from FRESH or JSON RESUME format.').option('-f --format <fmt>', 'FRESH or JRS format and optional version', void 0).action(function() {
var x;
x = splitSrcDest.call(this);
execute.call(this, x.src, x.dst, this.opts(), logMsg);
});
program.command('analyze')["arguments"]('<sources...>').option('--private', 'Include resume fields marked as private', false).description('Analyze one or more resumes.').action(function(sources) {
// Create the ANALYZE command
program.command('analyze').arguments('<sources...>').option('--private', 'Include resume fields marked as private', false).description('Analyze one or more resumes.').action(function(sources) {
execute.call(this, sources, [], this.opts(), logMsg);
});
program.command('peek')["arguments"]('<sources...>').description('Peek at a resume field or section').action(function(sources, sectionOrField) {
// Create the PEEK command
program.command('peek').arguments('<sources...>').description('Peek at a resume field or section').action(function(sources, sectionOrField) {
var dst;
dst = sources && sources.length > 1 ? [sources.pop()] : [];
dst = (sources && sources.length > 1) ? [sources.pop()] : [];
execute.call(this, sources, dst, this.opts(), logMsg);
});
// Create the BUILD command
program.command('build').alias('generate').option('-t --theme <theme>', 'Theme name or path').option('-n --no-prettify', 'Disable HTML prettification', true).option('-c --css <option>', 'CSS linking / embedding').option('-p --pdf <engine>', 'PDF generation engine').option('--no-sort', 'Sort resume sections by date', false).option('--tips', 'Display theme tips and warnings.', false).option('--private', 'Include resume fields marked as private', false).option('--no-escape', "Turn off encoding in Handlebars themes.", false).description('Generate resume to multiple formats').action(function(sources, targets, options) {
var x;
x = splitSrcDest.call(this);
execute.call(this, x.src, x.dst, this.opts(), logMsg);
});
program.command('help')["arguments"]('[command]').description('Get help on a HackMyResume command').action(function(cmd) {
// Create the HELP command
program.command('help').arguments('[command]').description('Get help on a HackMyResume command').action(function(cmd) {
var manPage;
cmd = cmd || 'use';
manPage = FS.readFileSync(PATH.join(__dirname, 'help/' + cmd + '.txt'), 'utf8');
@ -106,9 +122,6 @@ Definition of the `main` function.
}
};
/* Massage command-line args and setup Commander.js. */
initialize = function(ar, exitCallback) {
var o;
_exitCallback = exitCallback || process.exit;
@ -131,6 +144,7 @@ Definition of the `main` function.
return null;
}
o.silent || logMsg(_title);
// Emit debug prelude if --debug was specified
if (o.debug) {
_out.log(chalk.cyan('The -d or --debug switch was specified. DEBUG mode engaged.'));
_out.log('');
@ -138,9 +152,12 @@ Definition of the `main` function.
_out.log(chalk.cyan(PAD(' Node.js:', 25, null, PAD.RIGHT)) + chalk.cyan.bold(process.version));
_out.log(chalk.cyan(PAD(' HackMyResume:', 25, null, PAD.RIGHT)) + chalk.cyan.bold('v' + PKG.version));
_out.log(chalk.cyan(PAD(' FRESCA:', 25, null, PAD.RIGHT)) + chalk.cyan.bold(PKG.dependencies.fresca));
//_out.log(chalk.cyan(PAD(' fresh-themes:',25, null, PAD.RIGHT)) + chalk.cyan.bold( PKG.dependencies['fresh-themes'] ))
//_out.log(chalk.cyan(PAD(' fresh-jrs-converter:',25, null, PAD.RIGHT)) + chalk.cyan.bold( PKG.dependencies['fresh-jrs-converter'] ))
_out.log('');
}
_err.init(o.debug, o.assert, o.silent);
// Handle invalid verbs here (a bit easier here than in commander.js)...
if (o.verb && !HMR.verbs[o.verb] && !HMR.alias[o.verb] && o.verb !== 'help') {
_err.err({
fluenterror: HMSTATUS.invalidCommand,
@ -148,6 +165,7 @@ Definition of the `main` function.
attempted: o.orgVerb
}, true);
}
// Override the .missingArgument behavior
Command.prototype.missingArgument = function(name) {
if (this.name() !== 'help') {
_err.err({
@ -156,6 +174,7 @@ Definition of the `main` function.
}, true);
}
};
// Override the .helpInformation behavior
Command.prototype.helpInformation = function() {
var manPage;
manPage = FS.readFileSync(PATH.join(__dirname, 'help/use.txt'), 'utf8');
@ -167,17 +186,16 @@ Definition of the `main` function.
};
};
/* Init options prior to setting up command infrastructure. */
initOptions = function(ar) {
oVerb;
/* jshint ignore:end */
var args, cleanArgs, inf, isAssert, isDebug, isMono, isNoEscape, isSilent, oJSON, oVerb, optStr, optsIdx, verb, vidx;
verb = '';
args = ar.slice();
cleanArgs = args.slice(2);
oJSON;
if (cleanArgs.length) {
// Support case-insensitive sub-commands (build, generate, validate, etc)
vidx = _.findIndex(cleanArgs, function(v) {
return v[0] !== '-';
});
@ -185,6 +203,7 @@ Definition of the `main` function.
oVerb = cleanArgs[vidx];
verb = args[vidx + 2] = oVerb.trim().toLowerCase();
}
// Remove --options --opts -o and process separately
optsIdx = _.findIndex(cleanArgs, function(v) {
return v === '-o' || v === '--options' || v === '--opts';
});
@ -192,12 +211,11 @@ Definition of the `main` function.
optStr = cleanArgs[optsIdx + 1];
args.splice(optsIdx + 2, 2);
if (optStr && (optStr = optStr.trim())) {
//var myJSON = JSON.parse(optStr);
if (optStr[0] === '{') {
// TODO: remove use of evil(). - hacksalot
/* jshint ignore:start */
oJSON = eval('(' + optStr + ')');
/* jshint ignore:end */
oJSON = eval('(' + optStr + ')'); // jshint ignore:line <-- no worky
} else {
inf = safeLoadJSON(optStr);
if (!inf.ex) {
@ -209,6 +227,7 @@ Definition of the `main` function.
}
}
}
// Grab the --debug flag, --silent, --assert and --no-color flags
isDebug = _.some(args, function(v) {
return v === '-d' || v === '--debug';
});
@ -237,35 +256,35 @@ Definition of the `main` function.
};
};
/* Invoke a HackMyResume verb. */
execute = function(src, dst, opts, log) {
var prom, v;
// Create the verb
v = new HMR.verbs[this.name()]();
// Initialize command-specific options
loadOptions.call(this, opts, this.parent.jsonArgs);
// Set up error/output handling
_opts.errHandler = v;
_out.init(_opts);
// Hook up event notifications
v.on('hmr:status', function() {
return _out["do"].apply(_out, arguments);
return _out.do.apply(_out, arguments);
});
v.on('hmr:error', function() {
return _err.err.apply(_err, arguments);
});
// Invoke the verb using promise syntax
prom = v.invoke.call(v, src, dst, _opts, log);
prom.then(executeSuccess, executeFail);
};
/* Success handler for verb invocations. Calls process.exit by default */
executeSuccess = function(obj) {};
// Can't call _exitCallback here (process.exit) when PDF is running in BK
//_exitCallback 0; return
/* Failure handler for verb invocations. Calls process.exit by default */
executeFail = function(err) {
var finalErrorCode, msgs;
//console.dir err
finalErrorCode = -1;
if (err) {
if (err.fluenterror) {
@ -286,19 +305,16 @@ Definition of the `main` function.
_exitCallback(finalErrorCode);
};
/*
Initialize HackMyResume options.
TODO: Options loading is a little hacky, for two reasons:
- Commander.js idiosyncracies
- Need to accept JSON inputs from the command line.
*/
loadOptions = function(o, cmdO) {
// o and this.opts() seem to be the same (command-specific options)
// Load the specified options file (if any) and apply options
if (cmdO) {
o = EXTEND(true, o, cmdO);
}
// Merge in command-line options
o = EXTEND(true, o, this.opts());
// Kludge parent-level options until piping issue is resolved
if (this.parent.silent !== void 0 && this.parent.silent !== null) {
o.silent = this.parent.silent;
}
@ -318,9 +334,6 @@ Definition of the `main` function.
EXTEND(true, _opts, o);
};
/* Split multiple command-line filenames by the 'TO' keyword */
splitSrcDest = function() {
var params, splitAt;
params = this.parent.args.filter(function(j) {
@ -328,14 +341,17 @@ Definition of the `main` function.
});
if (params.length === 0) {
throw {
//tmpName = @name()
fluenterror: HMSTATUS.resumeNotFound,
verb: this.name(),
quit: true
};
}
// Find the TO keyword, if any
splitAt = _.findIndex(params, function(p) {
return p.toLowerCase() === 'to';
});
// TO can't be the last keyword
if (splitAt === params.length - 1 && splitAt !== -1) {
logMsg(chalk.yellow('Please ') + chalk.yellow.bold('specify an output file') + chalk.yellow(' for this operation or ') + chalk.yellow.bold('omit the TO keyword') + chalk.yellow('.'));
return;
@ -346,9 +362,6 @@ Definition of the `main` function.
};
};
/* Simple logging placeholder. */
logMsg = function() {
return _opts.silent || console.log.apply(console.log, arguments);
};

4
dist/cli/msg.js vendored
View File

@ -1,11 +1,9 @@
(function() {
/**
Message-handling routines for HackMyResume.
@module cli/msg
@license MIT. See LICENSE.md for details.
*/
(function() {
var PATH, YAML;
PATH = require('path');

32
dist/cli/out.js vendored
View File

@ -1,11 +1,9 @@
(function() {
/**
Output routines for HackMyResume.
@license MIT. See LICENSE.md for details.
@module cli/out
*/
(function() {
var EXTEND, FS, HANDLEBARS, HME, LO, M2C, OutputHandler, PATH, YAML, _, chalk, dbgStyle, pad, printf;
chalk = require('chalk');
@ -34,29 +32,26 @@ Output routines for HackMyResume.
dbgStyle = 'cyan';
/** A stateful output module. All HMR console output handled here. */
module.exports = OutputHandler = (function() {
function OutputHandler(opts) {
module.exports = OutputHandler = class OutputHandler {
constructor(opts) {
this.init(opts);
return;
}
OutputHandler.prototype.init = function(opts) {
init(opts) {
this.opts = EXTEND(true, this.opts || {}, opts);
this.msgs = YAML.load(PATH.join(__dirname, 'msg.yml')).events;
};
}
OutputHandler.prototype.log = function(msg) {
log(msg) {
var finished;
msg = msg || '';
printf = require('printf');
finished = printf.apply(printf, arguments);
return this.opts.silent || console.log(finished);
};
}
OutputHandler.prototype["do"] = function(evt) {
do(evt) {
var L, WRAP, adj, info, msg, msgs, numFormats, output, rawTpl, sty, style, suffix, template, that, themeName, tot;
that = this;
L = function() {
@ -65,6 +60,9 @@ Output routines for HackMyResume.
switch (evt.sub) {
case HME.begin:
return this.opts.debug && L(M2C(this.msgs.begin.msg, dbgStyle), evt.cmd.toUpperCase());
//when HME.beforeCreate
//L( M2C( this.msgs.beforeCreate.msg, 'green' ), evt.fmt, evt.file )
//break;
case HME.afterCreate:
L(M2C(this.msgs.beforeCreate.msg, evt.isError ? 'red' : 'green'), evt.fmt, evt.file);
break;
@ -166,11 +164,13 @@ Output routines for HackMyResume.
break;
case HME.afterPeek:
sty = evt.error ? 'red' : (evt.target !== void 0 ? 'green' : 'yellow');
// "Peeking at 'someKey' in 'someFile'."
if (evt.requested) {
L(M2C(this.msgs.beforePeek.msg[0], sty), evt.requested, evt.file);
} else {
L(M2C(this.msgs.beforePeek.msg[1], sty), evt.file);
}
// If the key was present, print it
if (evt.target !== void 0 && !evt.error) {
return console.dir(evt.target, {
depth: null,
@ -182,12 +182,10 @@ Output routines for HackMyResume.
return L(chalk.red(evt.error.inner.inner));
}
}
}
};
return OutputHandler;
})();
}).call(this);
//# sourceMappingURL=out.js.map

View File

@ -1,55 +1,59 @@
(function() {
/*
Event code definitions.
@module core/default-formats
@license MIT. See LICENSE.md for details.
*/
/** Supported resume formats. */
(function() {
module.exports = [
{
name: 'html',
ext: 'html',
gen: new (require('../generators/html-generator'))()
}, {
},
{
name: 'txt',
ext: 'txt',
gen: new (require('../generators/text-generator'))()
}, {
},
{
name: 'doc',
ext: 'doc',
fmt: 'xml',
gen: new (require('../generators/word-generator'))()
}, {
},
{
name: 'pdf',
ext: 'pdf',
fmt: 'html',
is: false,
gen: new (require('../generators/html-pdf-cli-generator'))()
}, {
},
{
name: 'png',
ext: 'png',
fmt: 'html',
is: false,
gen: new (require('../generators/html-png-generator'))()
}, {
},
{
name: 'md',
ext: 'md',
fmt: 'txt',
gen: new (require('../generators/markdown-generator'))()
}, {
},
{
name: 'json',
ext: 'json',
gen: new (require('../generators/json-generator'))()
}, {
},
{
name: 'yml',
ext: 'yml',
fmt: 'yml',
gen: new (require('../generators/json-yaml-generator'))()
}, {
},
{
name: 'latex',
ext: 'tex',
fmt: 'latex',

View File

@ -1,20 +1,20 @@
(function() {
/*
Event code definitions.
@module core/default-options
@license MIT. See LICENSE.md for details.
*/
(function() {
module.exports = {
theme: 'modern',
prettify: {
indent_size: 2,
unformatted: ['em', 'strong'],
max_char: 80
max_char: 80 // ← See lib/html.js in above-linked repo
}
};
// wrap_line_length: 120, ← Don't use this
}).call(this);
//# sourceMappingURL=default-options.js.map

View File

@ -1,11 +1,9 @@
(function() {
/*
Event code definitions.
@module core/event-codes
@license MIT. See LICENSE.md for details.
*/
(function() {
module.exports = {
error: -1,
success: 0,

View File

@ -1,18 +1,15 @@
(function() {
/**
The HackMyResume date representation.
@license MIT. See LICENSE.md for details.
@module core/fluent-date
*/
(function() {
var FluentDate, abbr, moment, months;
moment = require('moment');
require('../utils/string');
/**
Create a FluentDate from a string or Moment date object. There are a few date
formats to be aware of here.
@ -29,20 +26,17 @@ The HackMyResume date representation.
format or b) use an ISO format. For clarity, we handle these cases explicitly.
@class FluentDate
*/
FluentDate = (function() {
function FluentDate(dt) {
FluentDate = class FluentDate {
constructor(dt) {
this.rep = this.fmt(dt);
}
FluentDate.isCurrent = function(dt) {
static isCurrent(dt) {
return !dt || (String.is(dt) && /^(present|now|current)$/.test(dt));
}
};
return FluentDate;
})();
months = {};
abbr = {};
@ -64,20 +58,20 @@ The HackMyResume date representation.
throws = (throws === void 0 || throws === null) || throws;
if (typeof dt === 'string' || dt instanceof String) {
dt = dt.toLowerCase().trim();
if (/^(present|now|current)$/.test(dt)) {
if (/^(present|now|current)$/.test(dt)) { // "Present", "Now"
return moment();
} else if (/^\D+\s+\d{4}$/.test(dt)) {
} else if (/^\D+\s+\d{4}$/.test(dt)) { // "Mar 2015"
parts = dt.split(' ');
month = months[parts[0]] || abbr[parts[0]];
temp = parts[1] + '-' + ((ref = month < 10) != null ? ref : '0' + {
month: month.toString()
});
return moment(temp, 'YYYY-MM');
} else if (/^\d{4}-\d{1,2}$/.test(dt)) {
} else if (/^\d{4}-\d{1,2}$/.test(dt)) { // "2015-03", "1998-4"
return moment(dt, 'YYYY-MM');
} else if (/^\s*\d{4}\s*$/.test(dt)) {
} else if (/^\s*\d{4}\s*$/.test(dt)) { // "2015"
return moment(dt, 'YYYY');
} else if (/^\s*$/.test(dt)) {
} else if (/^\s*$/.test(dt)) { // "", " "
return moment();
} else {
mt = moment(dt);

View File

@ -1,11 +1,16 @@
(function() {
/**
Definition of the FRESHResume class.
@license MIT. See LICENSE.md for details.
@module core/fresh-resume
*/
(function() {
/**
Convert human-friendly dates into formal Moment.js dates for all collections.
We don't want to lose the raw textual date as entered by the user, so we store
the Moment-ified date as a separate property with a prefix of .safe. For ex:
job.startDate is the date as entered by the user. job.safeStartDate is the
parsed Moment.js date that we actually use in processing.
*/
var CONVERTER, FS, FluentDate, FreshResume, JRSResume, MD, PATH, XML, _, __, _parseDates, extend, moment, validator;
FS = require('fs');
@ -32,27 +37,20 @@ Definition of the FRESHResume class.
FluentDate = require('./fluent-date');
/**
A FRESH resume or CV. FRESH resumes are backed by JSON, and each FreshResume
object is an instantiation of that JSON decorated with utility methods.
@constructor
*/
FreshResume = (function() {
function FreshResume() {}
FreshResume = class FreshResume { // extends AbstractResume
/** Initialize the the FreshResume from JSON string data. */
FreshResume.prototype.parse = function(stringData, opts) {
parse(stringData, opts) {
var ref;
this.imp = (ref = this.imp) != null ? ref : {
raw: stringData
};
return this.parseJSON(JSON.parse(stringData), opts);
};
}
/**
Initialize the FreshResume from JSON.
@ -67,15 +65,17 @@ Definition of the FRESHResume class.
compute: Prepare computed resume totals.
}
*/
FreshResume.prototype.parseJSON = function(rep, opts) {
var ignoreList, privateList, ref, ref1, scrubbed, scrubber;
parseJSON(rep, opts) {
var ignoreList, privateList, ref, scrubbed, scrubber;
if (opts && opts.privatize) {
// Ignore any element with the 'ignore: true' or 'private: true' designator.
scrubber = require('../utils/resume-scrubber');
ref = scrubber.scrubResume(rep, opts), scrubbed = ref.scrubbed, ignoreList = ref.ignoreList, privateList = ref.privateList;
({scrubbed, ignoreList, privateList} = scrubber.scrubResume(rep, opts));
}
// Now apply the resume representation onto this object
extend(true, this, opts && opts.privatize ? scrubbed : rep);
if (!((ref1 = this.imp) != null ? ref1.processed : void 0)) {
if (!((ref = this.imp) != null ? ref.processed : void 0)) {
// Set up metadata TODO: Clean up metadata on the object model.
opts = opts || {};
if (opts.imp === void 0 || opts.imp) {
this.imp = this.imp || {};
@ -85,6 +85,7 @@ Definition of the FRESHResume class.
}
}
this.imp.processed = true;
// Parse dates, sort dates, and calculate computed values
(opts.date === void 0 || opts.date) && _parseDates.call(this);
(opts.sort === void 0 || opts.sort) && this.sort();
(opts.compute === void 0 || opts.compute) && (this.computed = {
@ -93,25 +94,26 @@ Definition of the FRESHResume class.
});
}
return this;
};
}
/** Save the sheet to disk (for environments that have disk access). */
FreshResume.prototype.save = function(filename) {
save(filename) {
this.imp.file = filename || this.imp.file;
FS.writeFileSync(this.imp.file, this.stringify(), 'utf8');
return this;
};
}
/**
Save the sheet to disk in a specific format, either FRESH or JSON Resume.
*/
FreshResume.prototype.saveAs = function(filename, format) {
saveAs(filename, format) {
var newRep, parts, safeFormat, useEdgeSchema;
// If format isn't specified, default to FRESH
safeFormat = (format && format.trim()) || 'FRESH';
// Validate against the FRESH version regex
// freshVersionReg = require '../utils/fresh-version-regex'
// if (not freshVersionReg().test( safeFormat ))
// throw badVer: safeFormat
parts = safeFormat.split('@');
if (parts[0] === 'FRESH') {
this.imp.file = filename || this.imp.file;
@ -128,8 +130,7 @@ Definition of the FRESHResume class.
};
}
return this;
};
}
/**
Duplicate this FreshResume instance.
@ -138,46 +139,39 @@ Definition of the FRESHResume class.
We do it this way to create a true clone of the object without re-running any
of the associated processing.
*/
FreshResume.prototype.dupe = function() {
dupe() {
var jso, rnew;
jso = extend(true, {}, this);
rnew = new FreshResume();
rnew.parseJSON(jso, {});
return rnew;
};
}
/**
Convert this object to a JSON string, sanitizing meta-properties along the
way.
*/
FreshResume.prototype.stringify = function() {
stringify() {
return FreshResume.stringify(this);
};
}
/**
Create a copy of this resume in which all string fields have been run through
a transformation function (such as a Markdown filter or XML encoder).
TODO: Move this out of FRESHResume.
*/
FreshResume.prototype.transformStrings = function(filt, transformer) {
transformStrings(filt, transformer) {
var ret, trx;
ret = this.dupe();
trx = require('../utils/string-transformer');
return trx(ret, filt, transformer);
};
}
/**
Create a copy of this resume in which all fields have been interpreted as
Markdown.
*/
FreshResume.prototype.markdownify = function() {
markdownify() {
var MDIN, trx;
MDIN = function(txt) {
return MD(txt || '').replace(/^\s*<p>|<\/p>\s*$/gi, '');
@ -189,44 +183,49 @@ Definition of the FRESHResume class.
return MDIN(val);
};
return this.transformStrings(['skills', 'url', 'start', 'end', 'date'], trx);
};
}
/**
Create a copy of this resume in which all fields have been interpreted as
Markdown.
*/
FreshResume.prototype.xmlify = function() {
xmlify() {
var trx;
trx = function(key, val) {
return XML(val);
};
return this.transformStrings([], trx);
};
}
/** Return the resume format. */
FreshResume.prototype.format = function() {
format() {
return 'FRESH';
};
}
/**
Return internal metadata. Create if it doesn't exist.
*/
FreshResume.prototype.i = function() {
i() {
return this.imp = this.imp || {};
};
}
/**
Return a unique list of all skills declared in the resume.
*/
// TODO: Several problems here:
// 1) Confusing name. Easily confused with the keyword-inspector module, which
// parses resume body text looking for these same keywords. This should probably
// be renamed.
FreshResume.prototype.keywords = function() {
// 2) Doesn't bother trying to integrate skills.list with skills.sets if they
// happen to declare different skills, and if skills.sets declares ONE skill and
// skills.list declared 50, only 1 skill will be registered.
// 3) In the future, skill.sets should only be able to use skills declared in
// skills.list. That is, skills.list is the official record of a candidate's
// declared skills. skills.sets is just a way of grouping those into skillsets
// for easier consumption.
keywords() {
var flatSkills;
flatSkills = [];
if (this.skills) {
@ -244,19 +243,17 @@ Definition of the FRESHResume class.
flatSkills = _.uniq(flatSkills);
}
return flatSkills;
};
}
/**
Reset the sheet to an empty state. TODO: refactor/review
*/
FreshResume.prototype.clear = function(clearMeta) {
clear(clearMeta) {
clearMeta = ((clearMeta === void 0) && true) || clearMeta;
if (clearMeta) {
delete this.imp;
}
delete this.computed;
delete this.computed; // Don't use Object.keys() here
delete this.employment;
delete this.service;
delete this.education;
@ -266,14 +263,12 @@ Definition of the FRESHResume class.
delete this.interests;
delete this.skills;
return delete this.social;
};
}
/**
Get a safe count of the number of things in a section.
*/
FreshResume.prototype.count = function(obj) {
count(obj) {
if (!obj) {
return 0;
}
@ -284,14 +279,11 @@ Definition of the FRESHResume class.
return obj.sets.length;
}
return obj.length || 0;
};
}
/** Add work experience to the sheet. */
FreshResume.prototype.add = function(moniker) {
add(moniker) {
var defSheet, newObject;
defSheet = FreshResume["default"]();
defSheet = FreshResume.default();
newObject = defSheet[moniker].history ? $.extend(true, {}, defSheet[moniker].history[0]) : moniker === 'skills' ? $.extend(true, {}, defSheet.skills.sets[0]) : $.extend(true, {}, defSheet[moniker][0]);
this[moniker] = this[moniker] || [];
if (this[moniker].history) {
@ -302,63 +294,53 @@ Definition of the FRESHResume class.
this[moniker].push(newObject);
}
return newObject;
};
}
/**
Determine if the sheet includes a specific social profile (eg, GitHub).
*/
FreshResume.prototype.hasProfile = function(socialNetwork) {
hasProfile(socialNetwork) {
socialNetwork = socialNetwork.trim().toLowerCase();
return this.social && _.some(this.social, function(p) {
return p.network.trim().toLowerCase() === socialNetwork;
});
};
}
/** Return the specified network profile. */
FreshResume.prototype.getProfile = function(socialNetwork) {
getProfile(socialNetwork) {
socialNetwork = socialNetwork.trim().toLowerCase();
return this.social && _.find(this.social, function(sn) {
return sn.network.trim().toLowerCase() === socialNetwork;
});
};
}
/**
Return an array of profiles for the specified network, for when the user
has multiple eg. GitHub accounts.
*/
FreshResume.prototype.getProfiles = function(socialNetwork) {
getProfiles(socialNetwork) {
socialNetwork = socialNetwork.trim().toLowerCase();
return this.social && _.filter(this.social, function(sn) {
return sn.network.trim().toLowerCase() === socialNetwork;
});
};
}
/** Determine if the sheet includes a specific skill. */
FreshResume.prototype.hasSkill = function(skill) {
hasSkill(skill) {
skill = skill.trim().toLowerCase();
return this.skills && _.some(this.skills, function(sk) {
return sk.keywords && _.some(sk.keywords, function(kw) {
return kw.trim().toLowerCase() === skill;
});
});
};
}
/** Validate the sheet against the FRESH Resume schema. */
FreshResume.prototype.isValid = function(info) {
isValid(info) {
var ret, schemaObj, validate;
schemaObj = require('fresh-resume-schema');
validator = require('is-my-json-valid');
validate = validator(schemaObj, {
validate = validator(schemaObj, { // See Note [1].
formats: {
date: /^\d{4}(?:-(?:0[0-9]{1}|1[0-2]{1})(?:-[0-9]{2})?)?$/
}
@ -369,21 +351,19 @@ Definition of the FRESHResume class.
this.imp.validationErrors = validate.errors;
}
return ret;
};
}
FreshResume.prototype.duration = function(unit) {
duration(unit) {
var inspector;
inspector = require('../inspectors/duration-inspector');
return inspector.run(this, 'employment.history', 'start', 'end', unit);
};
}
/**
Sort dated things on the sheet by start date descending. Assumes that dates
on the sheet have been processed with _parseDates().
*/
FreshResume.prototype.sort = function() {
sort() {
var byDateDesc, sortSection;
byDateDesc = function(a, b) {
if (a.safe.start.isBefore(b.safe.start)) {
@ -417,30 +397,24 @@ Definition of the FRESHResume class.
return (a.safe.date.isAfter(b.safe.date) && -1) || 0;
}
});
}
};
return FreshResume;
})();
/**
Get the default (starter) sheet.
*/
FreshResume["default"] = function() {
FreshResume.default = function() {
return new FreshResume().parseJSON(require('fresh-resume-starter').fresh);
};
/**
Convert the supplied FreshResume to a JSON string, sanitizing meta-properties
along the way.
*/
FreshResume.stringify = function(obj) {
var replacer;
replacer = function(key, value) {
replacer = function(key, value) { // Exclude these keys from stringification
var exKeys;
exKeys = ['imp', 'warnings', 'computed', 'filt', 'ctrl', 'index', 'safe', 'result', 'isModified', 'htmlPreview', 'display_progress_bar'];
if (_.some(exKeys, function(val) {
@ -454,19 +428,11 @@ Definition of the FRESHResume class.
return JSON.stringify(obj, replacer, 2);
};
/**
Convert human-friendly dates into formal Moment.js dates for all collections.
We don't want to lose the raw textual date as entered by the user, so we store
the Moment-ified date as a separate property with a prefix of .safe. For ex:
job.startDate is the date as entered by the user. job.safeStartDate is the
parsed Moment.js date that we actually use in processing.
*/
_parseDates = function() {
var _fmt, replaceDatesInObject, that;
_fmt = require('./fluent-date').fmt;
that = this;
// TODO: refactor recursion
replaceDatesInObject = function(obj) {
if (!obj) {
return;
@ -498,11 +464,15 @@ Definition of the FRESHResume class.
});
};
/** Export the Sheet function/ctor. */
module.exports = FreshResume;
// Note 1: Adjust default date validation to allow YYYY and YYYY-MM formats
// in addition to YYYY-MM-DD. The original regex:
// /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-[0-9]{2}$/
}).call(this);
//# sourceMappingURL=fresh-resume.js.map

View File

@ -1,11 +1,12 @@
(function() {
/**
Definition of the FRESHTheme class.
@module core/fresh-theme
@license MIT. See LICENSE.md for details.
*/
(function() {
/* Load and parse theme source files. */
/* Load a single theme file. */
/* Return a more friendly name for certain formats. */
var EXTEND, FRESHTheme, FS, HMSTATUS, PATH, READFILES, _, _load, _loadOne, friendlyName, loadSafeJson, moment, parsePath, pathExists, validator;
FS = require('fs');
@ -30,39 +31,47 @@ Definition of the FRESHTheme class.
READFILES = require('recursive-readdir-sync');
/* A representation of a FRESH theme asset.
@class FRESHTheme
*/
FRESHTheme = (function() {
function FRESHTheme() {
@class FRESHTheme */
FRESHTheme = class FRESHTheme {
constructor() {
this.baseFolder = 'src';
return;
}
/* Open and parse the specified theme. */
FRESHTheme.prototype.open = function(themeFolder) {
open(themeFolder) {
var cached, formatsHash, pathInfo, that, themeFile, themeInfo;
this.folder = themeFolder;
// Open the [theme-name].json file; should have the same name as folder
pathInfo = parsePath(themeFolder);
// Set up a formats hash for the theme
formatsHash = {};
// Load the theme
themeFile = PATH.join(themeFolder, 'theme.json');
themeInfo = loadSafeJson(themeFile);
if (themeInfo.ex) {
throw {
fluenterror: themeInfo.ex.op === 'parse' ? HMSTATUS.parseError : HMSTATUS.readError,
inner: themeInfo.ex.inner
fluenterror: themeInfo.ex.op === 'parse' ? HMSTATUS.parseError : HMSTATUS.readError
};
({
inner: themeInfo.ex.inner
});
}
that = this;
// Move properties from the theme JSON file to the theme object
EXTEND(true, this, themeInfo.json);
// Check for an "inherits" entry in the theme JSON.
if (this.inherits) {
cached = {};
_.each(this.inherits, function(th, key) {
var d, themePath, themesObj;
// First, see if this is one of the predefined FRESH themes. There are
// only a handful of these, but they may change over time, so we need to
// query the official source of truth: the fresh-themes repository, which
// mounts the themes conveniently by name to the module object, and which
// is embedded locally inside the HackMyResume installation.
// TODO: merge this code with
themesObj = require('fresh-themes');
if (_.has(themesObj.themes, th)) {
themePath = PATH.join(parsePath(require.resolve('fresh-themes')).dirname, '/themes/', th);
@ -74,45 +83,46 @@ Definition of the FRESHTheme class.
return formatsHash[key] = cached[th].getFormat(key);
});
}
// Load theme files
formatsHash = _load.call(this, formatsHash);
// Cache
this.formats = formatsHash;
// Set the official theme name
this.name = parsePath(this.folder).name;
return this;
};
}
/* Determine if the theme supports the specified output format. */
FRESHTheme.prototype.hasFormat = function(fmt) {
hasFormat(fmt) {
return _.has(this.formats, fmt);
};
}
/* Determine if the theme supports the specified output format. */
FRESHTheme.prototype.getFormat = function(fmt) {
getFormat(fmt) {
return this.formats[fmt];
}
};
return FRESHTheme;
})();
/* Load and parse theme source files. */
_load = function(formatsHash) {
var copyOnly, fmts, jsFiles, major, that, tplFolder;
that = this;
major = false;
tplFolder = PATH.join(this.folder, this.baseFolder);
copyOnly = ['.ttf', '.otf', '.png', '.jpg', '.jpeg', '.pdf'];
// Iterate over all files in the theme folder, producing an array, fmts,
// containing info for each file. While we're doing that, also build up
// the formatsHash object.
fmts = READFILES(tplFolder).map(function(absPath) {
return _loadOne.call(this, absPath, formatsHash, tplFolder);
}, this);
// Now, get all the CSS files...
this.cssFiles = fmts.filter(function(fmt) {
return fmt && (fmt.ext === 'css');
});
// For each CSS file, get its corresponding HTML file. It's possible that
// a theme can have a CSS file but *no* HTML file, as when a theme author
// creates a pure CSS override of an existing theme.
this.cssFiles.forEach(function(cssf) {
var idx;
idx = _.findIndex(fmts, function(fmt) {
@ -124,6 +134,8 @@ Definition of the FRESHTheme class.
return fmts[idx].cssPath = cssf.path;
} else {
if (that.inherits) {
// Found a CSS file without an HTML file in a theme that inherits
// from another theme. This is the override CSS file.
return that.overrides = {
file: cssf.path,
data: cssf.data
@ -131,6 +143,7 @@ Definition of the FRESHTheme class.
}
}
});
// Now, save all the javascript file paths to a theme property.
jsFiles = fmts.filter(function(fmt) {
return fmt && (fmt.ext === 'js');
});
@ -140,9 +153,6 @@ Definition of the FRESHTheme class.
return formatsHash;
};
/* Load a single theme file. */
_loadOne = function(absPath, formatsHash, tplFolder) {
var absPathSafe, act, defFormats, idx, isPrimary, obj, outFmt, pathInfo, portion, ref, ref1, reg, res;
pathInfo = parsePath(absPath);
@ -153,6 +163,8 @@ Definition of the FRESHTheme class.
outFmt = '';
act = 'copy';
isPrimary = false;
// If this is an "explicit" theme, all files of importance are specified in
// the "transform" section of the theme.json file.
if (this.explicit) {
outFmt = _.find(Object.keys(this.formats), function(fmtKey) {
var fmtVal;
@ -168,6 +180,9 @@ Definition of the FRESHTheme class.
}
}
if (!outFmt) {
// If this file lives in a specific format folder within the theme,
// such as "/latex" or "/html", then that format is the implicit output
// format for all files within the folder
portion = pathInfo.dirname.replace(tplFolder, '');
if (portion && portion.trim()) {
if (portion[1] === '_') {
@ -203,13 +218,16 @@ Definition of the FRESHTheme class.
return form.name === outFmt && pathInfo.extname !== '.css';
});
}
// Make sure we have a valid formatsHash
formatsHash[outFmt] = formatsHash[outFmt] || {
outFormat: outFmt,
files: []
};
// Move symlink descriptions from theme.json to the format
if ((ref = this.formats) != null ? (ref1 = ref[outFmt]) != null ? ref1.symLinks : void 0 : void 0) {
formatsHash[outFmt].symLinks = this.formats[outFmt].symLinks;
}
// Create the file representation object
obj = {
action: act,
primary: isPrimary,
@ -218,16 +236,15 @@ Definition of the FRESHTheme class.
ext: pathInfo.extname.slice(1),
title: friendlyName(outFmt),
pre: outFmt,
// outFormat: outFmt || pathInfo.name,
data: FS.readFileSync(absPath, 'utf8'),
css: null
};
// Add this file to the list of files for this format type.
formatsHash[outFmt].files.push(obj);
return obj;
};
/* Return a more friendly name for certain formats. */
friendlyName = function(val) {
var friendly;
val = (val && val.trim().toLowerCase()) || '';

View File

@ -1,11 +1,16 @@
(function() {
/**
Definition of the JRSResume class.
@license MIT. See LICENSE.md for details.
@module core/jrs-resume
*/
(function() {
/**
Convert human-friendly dates into formal Moment.js dates for all collections.
We don't want to lose the raw textual date as entered by the user, so we store
the Moment-ified date as a separate property with a prefix of .safe. For ex:
job.startDate is the date as entered by the user. job.safeStartDate is the
parsed Moment.js date that we actually use in processing.
*/
var CONVERTER, FS, JRSResume, MD, PATH, _, _parseDates, extend, moment, validator;
FS = require('fs');
@ -24,29 +29,24 @@ Definition of the JRSResume class.
moment = require('moment');
JRSResume = (function() {
/** Reset the sheet to an empty state. */
var clear;
/**
A JRS resume or CV. JRS resumes are backed by JSON, and each JRSResume object
is an instantiation of that JSON decorated with utility methods.
@class JRSResume
*/
JRSResume = (function() {
var clear;
function JRSResume() {}
class JRSResume { // extends AbstractResume
/** Initialize the the JSResume from string. */
JRSResume.prototype.parse = function(stringData, opts) {
parse(stringData, opts) {
var ref;
this.imp = (ref = this.imp) != null ? ref : {
raw: stringData
};
return this.parseJSON(JSON.parse(stringData), opts);
};
}
/**
Initialize the JRSResume object from JSON.
@ -61,16 +61,18 @@ Definition of the JRSResume class.
compute: Prepare computed resume totals.
}
*/
JRSResume.prototype.parseJSON = function(rep, opts) {
var ignoreList, privateList, ref, ref1, scrubbed, scrubber;
parseJSON(rep, opts) {
var ignoreList, privateList, ref, scrubbed, scrubber;
opts = opts || {};
if (opts.privatize) {
scrubber = require('../utils/resume-scrubber');
ref = scrubber.scrubResume(rep, opts), scrubbed = ref.scrubbed, ignoreList = ref.ignoreList, privateList = ref.privateList;
// Ignore any element with the 'ignore: true' or 'private: true' designator.
({scrubbed, ignoreList, privateList} = scrubber.scrubResume(rep, opts));
}
// Extend resume properties onto ourself.
extend(true, this, opts.privatize ? scrubbed : rep);
if (!((ref1 = this.imp) != null ? ref1.processed : void 0)) {
if (!((ref = this.imp) != null ? ref.processed : void 0)) {
// Set up metadata TODO: Clean up metadata on the object model.
opts = opts || {};
if (opts.imp === void 0 || opts.imp) {
this.imp = this.imp || {};
@ -81,6 +83,7 @@ Definition of the JRSResume class.
}
this.imp.processed = true;
}
// Parse dates, sort dates, and calculate computed values
(opts.date === void 0 || opts.date) && _parseDates.call(this);
(opts.sort === void 0 || opts.sort) && this.sort();
if (opts.compute === void 0 || opts.compute) {
@ -90,21 +93,17 @@ Definition of the JRSResume class.
};
}
return this;
};
}
/** Save the sheet to disk (for environments that have disk access). */
JRSResume.prototype.save = function(filename) {
save(filename) {
this.imp.file = filename || this.imp.file;
FS.writeFileSync(this.imp.file, this.stringify(this), 'utf8');
return this;
};
}
/** Save the sheet to disk in a specific format, either FRESH or JRS. */
JRSResume.prototype.saveAs = function(filename, format) {
saveAs(filename, format) {
var newRep, stringRep;
if (format === 'JRS') {
this.imp.file = filename || this.imp.file;
@ -115,23 +114,19 @@ Definition of the JRSResume class.
FS.writeFileSync(filename, stringRep, 'utf8');
}
return this;
};
}
/** Return the resume format. */
JRSResume.prototype.format = function() {
format() {
return 'JRS';
};
}
JRSResume.prototype.stringify = function() {
stringify() {
return JRSResume.stringify(this);
};
}
/** Return a unique list of all keywords across all skills. */
JRSResume.prototype.keywords = function() {
keywords() {
var flatSkills;
flatSkills = [];
if (this.skills && this.skills.length) {
@ -140,82 +135,53 @@ Definition of the JRSResume class.
});
}
return flatSkills;
};
}
/**
Return internal metadata. Create if it doesn't exist.
JSON Resume v0.0.0 doesn't allow additional properties at the root level,
so tuck this into the .basic sub-object.
*/
JRSResume.prototype.i = function() {
i() {
var ref;
return this.imp = (ref = this.imp) != null ? ref : {};
};
/** Reset the sheet to an empty state. */
clear = function(clearMeta) {
clearMeta = ((clearMeta === void 0) && true) || clearMeta;
if (clearMeta) {
delete this.imp;
}
delete this.basics.computed;
delete this.work;
delete this.volunteer;
delete this.education;
delete this.awards;
delete this.publications;
delete this.interests;
delete this.skills;
return delete this.basics.profiles;
};
/** Add work experience to the sheet. */
JRSResume.prototype.add = function(moniker) {
add(moniker) {
var defSheet, newObject;
defSheet = JRSResume["default"]();
defSheet = JRSResume.default();
newObject = $.extend(true, {}, defSheet[moniker][0]);
this[moniker] = this[moniker] || [];
this[moniker].push(newObject);
return newObject;
};
}
/** Determine if the sheet includes a specific social profile (eg, GitHub). */
JRSResume.prototype.hasProfile = function(socialNetwork) {
hasProfile(socialNetwork) {
socialNetwork = socialNetwork.trim().toLowerCase();
return this.basics.profiles && _.some(this.basics.profiles, function(p) {
return p.network.trim().toLowerCase() === socialNetwork;
});
};
}
/** Determine if the sheet includes a specific skill. */
JRSResume.prototype.hasSkill = function(skill) {
hasSkill(skill) {
skill = skill.trim().toLowerCase();
return this.skills && _.some(this.skills, function(sk) {
return sk.keywords && _.some(sk.keywords, function(kw) {
return kw.trim().toLowerCase() === skill;
});
});
};
}
/** Validate the sheet against the JSON Resume schema. */
JRSResume.prototype.isValid = function() {
isValid() { // TODO: ↓ fix this path ↓
var ret, schema, schemaObj, temp, validate;
schema = FS.readFileSync(PATH.join(__dirname, 'resume.json'), 'utf8');
schemaObj = JSON.parse(schema);
validator = require('is-my-json-valid');
validate = validator(schemaObj, {
validate = validator(schemaObj, { // Note [1]
formats: {
date: /^\d{4}(?:-(?:0[0-9]{1}|1[0-2]{1})(?:-[0-9]{2})?)?$/
}
@ -229,21 +195,19 @@ Definition of the JRSResume class.
this.imp.validationErrors = validate.errors;
}
return ret;
};
}
JRSResume.prototype.duration = function(unit) {
duration(unit) {
var inspector;
inspector = require('../inspectors/duration-inspector');
return inspector.run(this, 'work', 'startDate', 'endDate', unit);
};
}
/**
Sort dated things on the sheet by start date descending. Assumes that dates
on the sheet have been processed with _parseDates().
*/
JRSResume.prototype.sort = function() {
sort() {
var byDateDesc;
byDateDesc = function(a, b) {
if (a.safeStartDate.isBefore(b.safeStartDate)) {
@ -269,56 +233,69 @@ Definition of the JRSResume class.
return (a.safeReleaseDate.isAfter(b.safeReleaseDate) && -1) || 0;
}
});
};
}
JRSResume.prototype.dupe = function() {
dupe() {
var rnew;
rnew = new JRSResume();
rnew.parse(this.stringify(), {});
return rnew;
};
}
/**
Create a copy of this resume in which all fields have been interpreted as
Markdown.
*/
JRSResume.prototype.harden = function() {
harden() {
var HD, HDIN, ret, transformer;
ret = this.dupe();
HD = function(txt) {
return '@@@@~' + txt + '~@@@@';
};
HDIN = function(txt) {
//return MD(txt || '' ).replace(/^\s*<p>|<\/p>\s*$/gi, '');
return HD(txt);
};
transformer = require('../utils/string-transformer');
return transformer(ret, ['skills', 'url', 'website', 'startDate', 'endDate', 'releaseDate', 'date', 'phone', 'email', 'address', 'postalCode', 'city', 'country', 'region', 'safeStartDate', 'safeEndDate'], function(key, val) {
return HD(val);
});
}
};
clear = function(clearMeta) {
clearMeta = ((clearMeta === void 0) && true) || clearMeta;
if (clearMeta) {
delete this.imp;
}
delete this.basics.computed; // Don't use Object.keys() here
delete this.work;
delete this.volunteer;
delete this.education;
delete this.awards;
delete this.publications;
delete this.interests;
delete this.skills;
return delete this.basics.profiles;
};
return JRSResume;
})();
}).call(this);
/** Get the default (empty) sheet. */
JRSResume["default"] = function() {
JRSResume.default = function() {
return new JRSResume().parseJSON(require('fresh-resume-starter').jrs);
};
/**
Convert this object to a JSON string, sanitizing meta-properties along the
way. Don't override .toString().
*/
JRSResume.stringify = function(obj) {
var replacer;
replacer = function(key, value) {
replacer = function(key, value) { // Exclude these keys from stringification
var temp;
temp = _.some(['imp', 'warnings', 'computed', 'filt', 'ctrl', 'index', 'safeStartDate', 'safeEndDate', 'safeDate', 'safeReleaseDate', 'result', 'isModified', 'htmlPreview', 'display_progress_bar'], function(val) {
return key.trim() === val;
@ -332,15 +309,6 @@ Definition of the JRSResume class.
return JSON.stringify(obj, replacer, 2);
};
/**
Convert human-friendly dates into formal Moment.js dates for all collections.
We don't want to lose the raw textual date as entered by the user, so we store
the Moment-ified date as a separate property with a prefix of .safe. For ex:
job.startDate is the date as entered by the user. job.safeStartDate is the
parsed Moment.js date that we actually use in processing.
*/
_parseDates = function() {
var _fmt;
_fmt = require('./fluent-date').fmt;
@ -364,11 +332,9 @@ Definition of the JRSResume class.
});
};
/**
Export the JRSResume function/ctor.
*/
module.exports = JRSResume;
}).call(this);

View File

@ -1,11 +1,9 @@
(function() {
/**
Definition of the JRSTheme class.
@module core/jrs-theme
@license MIT. See LICENSE.MD for details.
*/
(function() {
var JRSTheme, PATH, _, errors, parsePath, pathExists;
_ = require('underscore');
@ -18,32 +16,30 @@ Definition of the JRSTheme class.
errors = require('./status-codes');
/**
The JRSTheme class is a representation of a JSON Resume theme asset.
@class JRSTheme
*/
JRSTheme = (function() {
function JRSTheme() {}
JRSTheme = class JRSTheme {
/**
Open and parse the specified JRS theme.
@method open
*/
JRSTheme.prototype.open = function(thFolder) {
open(thFolder) {
var pathInfo, pkgJsonPath, thApi, thPkg;
this.folder = thFolder;
pathInfo = parsePath(thFolder);
// Open and parse the theme's package.json file
pkgJsonPath = PATH.join(thFolder, 'package.json');
if (pathExists(pkgJsonPath)) {
thApi = require(thFolder);
thPkg = require(pkgJsonPath);
thApi = require(thFolder); // Requiring the folder yields whatever the package.json's "main" is set to
thPkg = require(pkgJsonPath); // Get the package.json as JSON
this.name = thPkg.name;
this.render = (thApi && thApi.render) || void 0;
this.engine = 'jrs';
// Create theme formats (HTML and PDF). Just add the bare minimum mix of
// properties necessary to allow JSON Resume themes to share a rendering
// path with FRESH themes.
this.formats = {
html: {
outFormat: 'html',
@ -76,32 +72,26 @@ Definition of the JRSTheme class.
};
}
return this;
};
}
/**
Determine if the theme supports the output format.
@method hasFormat
*/
JRSTheme.prototype.hasFormat = function(fmt) {
hasFormat(fmt) {
return _.has(this.formats, fmt);
};
}
/**
Return the requested output format.
@method getFormat
*/
JRSTheme.prototype.getFormat = function(fmt) {
getFormat(fmt) {
return this.formats[fmt];
}
};
return JRSTheme;
})();
module.exports = JRSTheme;
}).call(this);

View File

@ -1,11 +1,13 @@
(function() {
/**
Definition of the ResumeFactory class.
@license MIT. See LICENSE.md for details.
@module core/resume-factory
*/
(function() {
/**
A simple factory class for FRESH and JSON Resumes.
@class ResumeFactory
*/
var FS, HME, HMS, ResumeConverter, ResumeFactory, SyntaxErrorEx, _, _parse, chalk, resumeDetect;
FS = require('fs');
@ -26,14 +28,7 @@ Definition of the ResumeFactory class.
require('string.prototype.startswith');
/**
A simple factory class for FRESH and JSON Resumes.
@class ResumeFactory
*/
ResumeFactory = module.exports = {
/**
Load one or more resumes from disk.
@ -47,31 +42,38 @@ Definition of the ResumeFactory class.
sort: false
}
}
*/
load: function(sources, opts, emitter) {
return sources.map(function(src) {
return this.loadOne(src, opts, emitter);
}, this);
},
/** Load a single resume from disk. */
loadOne: function(src, opts, emitter) {
var ResumeClass, info, json, orgFormat, reqLib, rez, toFormat;
toFormat = opts.format;
toFormat = opts.format; // Can be null
// Get the destination format. Can be 'fresh', 'jrs', or null/undefined.
toFormat && (toFormat = toFormat.toLowerCase().trim());
// Load and parse the resume JSON
info = _parse(src, opts, emitter);
if (info.fluenterror) {
return info;
}
// Determine the resume format: FRESH or JRS
json = info.json;
orgFormat = resumeDetect(json);
if (orgFormat === 'unk') {
info.fluenterror = HMS.unknownSchema;
return info;
}
// Convert between formats if necessary
if (toFormat && (orgFormat !== toFormat)) {
json = ResumeConverter['to' + toFormat.toUpperCase()](json);
}
// Objectify the resume, that is, convert it from JSON to a FRESHResume
// or JRSResume object.
rez = null;
if (opts.objectify) {
reqLib = '../core/' + (toFormat || orgFormat) + '-resume';
@ -88,9 +90,10 @@ Definition of the ResumeFactory class.
};
_parse = function(fileName, opts, eve) {
var orgFormat, rawData, ret;
var err, orgFormat, rawData, ret;
rawData = null;
try {
// Read the file
eve && eve.stat(HME.beforeRead, {
file: fileName
});
@ -112,10 +115,12 @@ Definition of the ResumeFactory class.
fmt: orgFormat
});
return ret;
} catch (_error) {
} catch (error) {
err = error;
return {
// Can be ENOENT, EACCES, SyntaxError, etc.
fluenterror: rawData ? HMS.parseError : HMS.readError,
inner: _error,
inner: err,
raw: rawData,
file: fileName
};

View File

@ -1,11 +1,9 @@
(function() {
/**
Status codes for HackMyResume.
@module core/status-codes
@license MIT. See LICENSE.MD for details.
*/
(function() {
module.exports = {
success: 0,
themeNotFound: 1,

View File

@ -1,39 +1,33 @@
(function() {
/**
Definition of the BaseGenerator class.
@module generators/base-generator
@license MIT. See LICENSE.md for details.
*/
var BaseGenerator;
/**
The BaseGenerator class is the root of the generator hierarchy. Functionality
common to ALL generators lives here.
*/
(function() {
var BaseGenerator;
module.exports = BaseGenerator = (function() {
class BaseGenerator {
/** Base-class initialize. */
function BaseGenerator(format) {
constructor(format) {
this.format = format;
}
};
/** Status codes. */
BaseGenerator.prototype.codes = require('../core/status-codes');
/** Generator options. */
BaseGenerator.prototype.opts = {};
return BaseGenerator;
})();
}).call(this);
}).call(this);

View File

@ -1,14 +1,10 @@
(function() {
/**
Definition of the HTMLGenerator class.
@module generators/html-generator
@license MIT. See LICENSE.md for details.
*/
(function() {
var FS, HTML, HtmlGenerator, PATH, TemplateGenerator,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
var FS, HTML, HtmlGenerator, PATH, TemplateGenerator;
TemplateGenerator = require('./template-generator');
@ -20,20 +16,16 @@ Definition of the HTMLGenerator class.
require('string.prototype.endswith');
module.exports = HtmlGenerator = (function(superClass) {
extend(HtmlGenerator, superClass);
function HtmlGenerator() {
HtmlGenerator.__super__.constructor.call(this, 'html');
module.exports = HtmlGenerator = class HtmlGenerator extends TemplateGenerator {
constructor() {
super('html');
}
/**
Copy satellite CSS files to the destination and optionally pretty-print
the HTML resume prior to saving.
*/
HtmlGenerator.prototype.onBeforeSave = function(info) {
onBeforeSave(info) {
if (info.outputFile.endsWith('.css')) {
return info.mk;
}
@ -42,12 +34,10 @@ Definition of the HTMLGenerator class.
} else {
return info.mk;
}
}
};
return HtmlGenerator;
})(TemplateGenerator);
}).call(this);
//# sourceMappingURL=html-generator.js.map

View File

@ -1,14 +1,10 @@
(function() {
/**
Definition of the HtmlPdfCLIGenerator class.
@module generators/html-pdf-generator.js
@license MIT. See LICENSE.md for details.
*/
(function() {
var FS, HMSTATUS, HtmlPdfCLIGenerator, PATH, SLASH, SPAWN, TemplateGenerator, _, engines,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
var FS, HMSTATUS, HtmlPdfCLIGenerator, PATH, SLASH, SPAWN, TemplateGenerator, _, engines;
TemplateGenerator = require('./template-generator');
@ -24,26 +20,21 @@ Definition of the HtmlPdfCLIGenerator class.
SPAWN = require('../utils/safe-spawn');
/**
An HTML-driven PDF resume generator for HackMyResume. Talks to Phantom,
wkhtmltopdf, and other PDF engines over a CLI (command-line interface).
If an engine isn't installed for a particular platform, error out gracefully.
*/
module.exports = HtmlPdfCLIGenerator = (function(superClass) {
extend(HtmlPdfCLIGenerator, superClass);
function HtmlPdfCLIGenerator() {
HtmlPdfCLIGenerator.__super__.constructor.call(this, 'pdf', 'html');
module.exports = HtmlPdfCLIGenerator = class HtmlPdfCLIGenerator extends TemplateGenerator {
constructor() {
super('pdf', 'html');
}
/** Generate the binary PDF. */
HtmlPdfCLIGenerator.prototype.onBeforeSave = function(info) {
onBeforeSave(info) {
var safe_eng;
if (info.ext !== 'html' && info.ext !== 'pdf') {
//console.dir _.omit( info, 'mk' ), depth: null, colors: true
return info.mk;
}
safe_eng = info.opts.pdf || 'wkhtmltopdf';
@ -53,32 +44,27 @@ Definition of the HtmlPdfCLIGenerator class.
if (_.has(engines, safe_eng)) {
this.errHandler = info.opts.errHandler;
engines[safe_eng].call(this, info.mk, info.outputFile, info.opts, this.onError);
return null;
return null; // halt further processing
}
}
};
/* Low-level error callback for spawn(). May be called after HMR process
termination, so object references may not be valid here. That's okay; if
the references are invalid, the error was already logged. We could use
spawn-watch here but that causes issues on legacy Node.js.
*/
HtmlPdfCLIGenerator.prototype.onError = function(ex, param) {
spawn-watch here but that causes issues on legacy Node.js. */
onError(ex, param) {
var ref;
if ((ref = param.errHandler) != null) {
if (typeof ref.err === "function") {
ref.err(HMSTATUS.pdfGeneration, ex);
}
}
}
};
return HtmlPdfCLIGenerator;
})(TemplateGenerator);
// TODO: Move each engine to a separate module
engines = {
/**
Generate a PDF from HTML using wkhtmltopdf's CLI interface.
Spawns a child process with `wkhtmltopdf <source> <target>`. wkhtmltopdf
@ -88,8 +74,10 @@ Definition of the HtmlPdfCLIGenerator class.
*/
wkhtmltopdf: function(markup, fOut, opts, on_error) {
var tempFile, wkargs, wkopts;
// Save the markup to a temporary file
tempFile = fOut.replace(/\.pdf$/i, '.pdf.html');
FS.writeFileSync(tempFile, markup, 'utf8');
// Prepare wkhtmltopdf arguments.
wkopts = _.extend({
'margin-top': '10mm',
'margin-bottom': '10mm'
@ -100,7 +88,6 @@ Definition of the HtmlPdfCLIGenerator class.
wkargs = wkopts.concat([tempFile, fOut]);
SPAWN('wkhtmltopdf', wkargs, false, on_error, this);
},
/**
Generate a PDF from HTML using Phantom's CLI interface.
Spawns a child process with `phantomjs <script> <source> <target>`. Phantom
@ -110,6 +97,7 @@ Definition of the HtmlPdfCLIGenerator class.
*/
phantomjs: function(markup, fOut, opts, on_error) {
var destPath, scriptPath, sourcePath, tempFile;
// Save the markup to a temporary file
tempFile = fOut.replace(/\.pdf$/i, '.pdf.html');
FS.writeFileSync(tempFile, markup, 'utf8');
scriptPath = PATH.relative(process.cwd(), PATH.resolve(__dirname, '../utils/rasterize.js'));
@ -118,7 +106,6 @@ Definition of the HtmlPdfCLIGenerator class.
destPath = SLASH(PATH.relative(process.cwd(), fOut));
SPAWN('phantomjs', [scriptPath, sourcePath, destPath], false, on_error, this);
},
/**
Generate a PDF from HTML using WeasyPrint's CLI interface.
Spawns a child process with `weasyprint <source> <target>`. Weasy Print
@ -127,6 +114,7 @@ Definition of the HtmlPdfCLIGenerator class.
*/
weasyprint: function(markup, fOut, opts, on_error) {
var tempFile;
// Save the markup to a temporary file
tempFile = fOut.replace(/\.pdf$/i, '.pdf.html');
FS.writeFileSync(tempFile, markup, 'utf8');
SPAWN('weasyprint', [tempFile, fOut], false, on_error, this);

View File

@ -1,14 +1,17 @@
(function() {
/**
Definition of the HtmlPngGenerator class.
@module generators/html-png-generator
@license MIT. See LICENSE.MD for details.
*/
(function() {
var FS, HTML, HtmlPngGenerator, PATH, SLASH, SPAWN, TemplateGenerator, phantom,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
/**
Generate a PDF from HTML using Phantom's CLI interface.
Spawns a child process with `phantomjs <script> <source> <target>`. Phantom
must be installed and path-accessible.
TODO: If HTML generation has run, reuse that output
TODO: Local web server to ease Phantom rendering
*/
var FS, HTML, HtmlPngGenerator, PATH, SLASH, SPAWN, TemplateGenerator, phantom;
TemplateGenerator = require('./template-generator');
@ -22,21 +25,18 @@ Definition of the HtmlPngGenerator class.
PATH = require('path');
/**
An HTML-based PNG resume generator for HackMyResume.
*/
module.exports = HtmlPngGenerator = (function(superClass) {
extend(HtmlPngGenerator, superClass);
function HtmlPngGenerator() {
HtmlPngGenerator.__super__.constructor.call(this, 'png', 'html');
module.exports = HtmlPngGenerator = class HtmlPngGenerator extends TemplateGenerator {
constructor() {
super('png', 'html');
}
HtmlPngGenerator.prototype.invoke = function(rez, themeMarkup, cssInfo, opts) {};
invoke(rez, themeMarkup, cssInfo, opts) {}
HtmlPngGenerator.prototype.generate = function(rez, f, opts) {
// TODO: Not currently called or callable.
generate(rez, f, opts) {
var htmlFile, htmlResults;
htmlResults = opts.targets.filter(function(t) {
return t.fmt.outFormat === 'html';
@ -45,23 +45,13 @@ Definition of the HtmlPngGenerator class.
return fl.info.ext === 'html';
});
phantom(htmlFile[0].data, f);
}
};
return HtmlPngGenerator;
})(TemplateGenerator);
/**
Generate a PDF from HTML using Phantom's CLI interface.
Spawns a child process with `phantomjs <script> <source> <target>`. Phantom
must be installed and path-accessible.
TODO: If HTML generation has run, reuse that output
TODO: Local web server to ease Phantom rendering
*/
phantom = function(markup, fOut) {
var destPath, info, scriptPath, sourcePath, tempFile;
// Save the markup to a temporary file
tempFile = fOut.replace(/\.png$/i, '.png.html');
FS.writeFileSync(tempFile, markup, 'utf8');
scriptPath = SLASH(PATH.relative(process.cwd(), PATH.resolve(__dirname, '../utils/rasterize.js')));

View File

@ -1,14 +1,10 @@
(function() {
/**
Definition of the JsonGenerator class.
@module generators/json-generator
@license MIT. See LICENSE.md for details.
*/
(function() {
var BaseGenerator, FJCV, FS, JsonGenerator, _,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
var BaseGenerator, FJCV, FS, JsonGenerator, _;
BaseGenerator = require('./base-generator');
@ -18,30 +14,25 @@ Definition of the JsonGenerator class.
FJCV = require('fresh-jrs-converter');
/** The JsonGenerator generates a FRESH or JRS resume as an output. */
module.exports = JsonGenerator = (function(superClass) {
extend(JsonGenerator, superClass);
function JsonGenerator() {
JsonGenerator.__super__.constructor.call(this, 'json');
module.exports = JsonGenerator = class JsonGenerator extends BaseGenerator {
constructor() {
super('json');
}
JsonGenerator.prototype.invoke = function(rez) {
invoke(rez) {
var altRez;
altRez = FJCV['to' + (rez.format() === 'FRESH' ? 'JRS' : 'FRESH')](rez);
return altRez = FJCV.toSTRING(altRez);
};
}
JsonGenerator.prototype.generate = function(rez, f) {
//altRez.stringify()
generate(rez, f) {
FS.writeFileSync(f, this.invoke(rez), 'utf8');
}
};
return JsonGenerator;
})(BaseGenerator);
}).call(this);
//# sourceMappingURL=json-generator.js.map

View File

@ -1,14 +1,10 @@
(function() {
/**
Definition of the JsonYamlGenerator class.
@module generators/json-yaml-generator
@license MIT. See LICENSE.md for details.
*/
(function() {
var BaseGenerator, FS, JsonYamlGenerator, YAML,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
var BaseGenerator, FS, JsonYamlGenerator, YAML;
BaseGenerator = require('./base-generator');
@ -16,35 +12,29 @@ Definition of the JsonYamlGenerator class.
YAML = require('yamljs');
/**
JsonYamlGenerator takes a JSON resume object and translates it directly to
JSON without a template, producing an equivalent YAML-formatted resume. See
also YamlGenerator (yaml-generator.js).
*/
module.exports = JsonYamlGenerator = (function(superClass) {
extend(JsonYamlGenerator, superClass);
function JsonYamlGenerator() {
JsonYamlGenerator.__super__.constructor.call(this, 'yml');
module.exports = JsonYamlGenerator = class JsonYamlGenerator extends BaseGenerator {
constructor() {
super('yml');
}
JsonYamlGenerator.prototype.invoke = function(rez, themeMarkup, cssInfo, opts) {
return YAML.stringify(JSON.parse(rez.stringify()), Infinity, 2);
};
invoke(rez, themeMarkup, cssInfo, opts) {
return YAML.stringify(JSON.parse(rez.stringify()), 2e308, 2);
}
JsonYamlGenerator.prototype.generate = function(rez, f, opts) {
generate(rez, f, opts) {
var data;
data = YAML.stringify(JSON.parse(rez.stringify()), Infinity, 2);
data = YAML.stringify(JSON.parse(rez.stringify()), 2e308, 2);
FS.writeFileSync(f, data, 'utf8');
return data;
}
};
return JsonYamlGenerator;
})(BaseGenerator);
}).call(this);
//# sourceMappingURL=json-yaml-generator.js.map

View File

@ -1,32 +1,22 @@
(function() {
/**
Definition of the LaTeXGenerator class.
@module generators/latex-generator
@license MIT. See LICENSE.md for details.
*/
(function() {
var LaTeXGenerator, TemplateGenerator,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
var LaTeXGenerator, TemplateGenerator;
TemplateGenerator = require('./template-generator');
/**
LaTeXGenerator generates a LaTeX resume via TemplateGenerator.
*/
module.exports = LaTeXGenerator = (function(superClass) {
extend(LaTeXGenerator, superClass);
function LaTeXGenerator() {
LaTeXGenerator.__super__.constructor.call(this, 'latex', 'tex');
module.exports = LaTeXGenerator = class LaTeXGenerator extends TemplateGenerator {
constructor() {
super('latex', 'tex');
}
return LaTeXGenerator;
})(TemplateGenerator);
};
}).call(this);

View File

@ -1,32 +1,22 @@
(function() {
/**
Definition of the MarkdownGenerator class.
@module generators/markdown-generator
@license MIT. See LICENSE.md for details.
*/
(function() {
var MarkdownGenerator, TemplateGenerator,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
var MarkdownGenerator, TemplateGenerator;
TemplateGenerator = require('./template-generator');
/**
MarkdownGenerator generates a Markdown-formatted resume via TemplateGenerator.
*/
module.exports = MarkdownGenerator = (function(superClass) {
extend(MarkdownGenerator, superClass);
function MarkdownGenerator() {
MarkdownGenerator.__super__.constructor.call(this, 'md', 'txt');
module.exports = MarkdownGenerator = class MarkdownGenerator extends TemplateGenerator {
constructor() {
super('md', 'txt');
}
return MarkdownGenerator;
})(TemplateGenerator);
};
}).call(this);

View File

@ -1,14 +1,13 @@
(function() {
/**
Definition of the TemplateGenerator class. TODO: Refactor
@module generators/template-generator
@license MIT. See LICENSE.md for details.
*/
(function() {
var BaseGenerator, EXTEND, FRESHTheme, FS, JRSTheme, MD, MKDIRP, PATH, TemplateGenerator, XML, _, _defaultOpts, _reg, createSymLinks, freeze, parsePath, unfreeze,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
/** Default template generator options. */
/** Freeze newlines for protection against errant JST parsers. */
/** Unfreeze newlines when the coast is clear. */
var BaseGenerator, EXTEND, FRESHTheme, FS, JRSTheme, MD, MKDIRP, PATH, TemplateGenerator, XML, _, _defaultOpts, _reg, createSymLinks, freeze, parsePath, unfreeze;
FS = require('fs-extra');
@ -32,46 +31,38 @@ Definition of the TemplateGenerator class. TODO: Refactor
JRSTheme = require('../core/jrs-theme');
/**
TemplateGenerator performs resume generation via local Handlebar or Underscore
style template expansion and is appropriate for text-based formats like HTML,
plain text, and XML versions of Microsoft Word, Excel, and OpenOffice.
@class TemplateGenerator
*/
module.exports = TemplateGenerator = (function(superClass) {
extend(TemplateGenerator, superClass);
module.exports = TemplateGenerator = class TemplateGenerator extends BaseGenerator {
/** Constructor. Set the output format and template format for this
generator. Will usually be called by a derived generator such as
HTMLGenerator or MarkdownGenerator.
*/
function TemplateGenerator(outputFormat, templateFormat, cssFile) {
TemplateGenerator.__super__.constructor.call(this, outputFormat);
HTMLGenerator or MarkdownGenerator. */
constructor(outputFormat, templateFormat, cssFile) {
super(outputFormat);
this.tplFormat = templateFormat || outputFormat;
return;
}
/** Generate a resume using string-based inputs and outputs without touching
the filesystem.
@method invoke
@param rez A FreshResume object.
@param opts Generator options.
@returns {Array} An array of objects representing the generated output
files.
*/
TemplateGenerator.prototype.invoke = function(rez, opts) {
files. */
invoke(rez, opts) {
var curFmt, results;
opts = opts ? (this.opts = EXTEND(true, {}, _defaultOpts, opts)) : this.opts;
// Sort such that CSS files are processed before others
curFmt = opts.themeObj.getFormat(this.format);
curFmt.files = _.sortBy(curFmt.files, function(fi) {
return fi.ext !== 'css';
});
// Run the transformation!
results = curFmt.files.map(function(tplInfo, idx) {
var trx;
if (tplInfo.action === 'transform') {
@ -95,25 +86,30 @@ Definition of the TemplateGenerator class. TODO: Refactor
return {
files: results
};
};
}
/** Generate a resume using file-based inputs and outputs. Requires access
to the local filesystem.
@method generate
@param rez A FreshResume object.
@param f Full path to the output resume file to generate.
@param opts Generator options.
*/
TemplateGenerator.prototype.generate = function(rez, f, opts) {
@param opts Generator options. */
generate(rez, f, opts) {
var curFmt, genInfo, outFolder;
// Prepare
this.opts = EXTEND(true, {}, _defaultOpts, opts);
// Call the string-based generation method
genInfo = this.invoke(rez, null);
outFolder = parsePath(f).dirname;
curFmt = opts.themeObj.getFormat(this.format);
// Process individual files within this format. For example, the HTML
// output format for a theme may have multiple HTML files, CSS files,
// etc. Process them here.
genInfo.files.forEach(function(file) {
var thisFilePath;
// console.dir _.omit(file.info,'cssData','data','css' )
// Pre-processing
file.info.orgPath = file.info.orgPath || '';
thisFilePath = file.info.primary ? f : PATH.join(outFolder, file.info.orgPath);
if (file.info.action !== 'copy' && this.onBeforeSave) {
@ -129,7 +125,9 @@ Definition of the TemplateGenerator class. TODO: Refactor
}
}
if (typeof opts.beforeWrite === "function") {
opts.beforeWrite(thisFilePath);
opts.beforeWrite({
data: thisFilePath
});
}
MKDIRP.sync(PATH.dirname(thisFilePath));
if (file.info.action !== 'copy') {
@ -141,8 +139,11 @@ Definition of the TemplateGenerator class. TODO: Refactor
FS.copySync(file.info.path, thisFilePath);
}
if (typeof opts.afterWrite === "function") {
opts.afterWrite(thisFilePath);
opts.afterWrite({
data: thisFilePath
});
}
// Post-processing
if (this.onAfterSave) {
return this.onAfterSave({
outputFile: fileName,
@ -151,10 +152,10 @@ Definition of the TemplateGenerator class. TODO: Refactor
});
}
}, this);
// Some themes require a symlink structure. If so, create it.
createSymLinks(curFmt, outFolder);
return genInfo;
};
}
/** Perform a single resume resume transformation using string-based inputs
and outputs without touching the local file system.
@ -162,10 +163,8 @@ Definition of the TemplateGenerator class. TODO: Refactor
@param jst The stringified template data
@param format The format name, such as "html" or "latex"
@param cssInfo Needs to be refactored.
@param opts Options and passthrough data.
*/
TemplateGenerator.prototype.transform = function(json, jst, format, opts, theme, curFmt) {
@param opts Options and passthrough data. */
transform(json, jst, format, opts, theme, curFmt) {
var eng, result;
if (this.opts.freezeBreaks) {
jst = freeze(jst);
@ -176,29 +175,30 @@ Definition of the TemplateGenerator class. TODO: Refactor
result = unfreeze(result);
}
return result;
}
};
return TemplateGenerator;
})(BaseGenerator);
createSymLinks = function(curFmt, outFolder) {
// Some themes require a symlink structure. If so, create it.
if (curFmt.symLinks) {
Object.keys(curFmt.symLinks).forEach(function(loc) {
var absLoc, absTarg, succeeded, type;
var absLoc, absTarg, err, succeeded, type;
absLoc = PATH.join(outFolder, loc);
absTarg = PATH.join(PATH.dirname(absLoc), curFmt.symLinks[loc]);
// Set type to 'file', 'dir', or 'junction' (Windows only)
type = parsePath(absLoc).extname ? 'file' : 'junction';
try {
return FS.symlinkSync(absTarg, absLoc, type);
} catch (_error) {
} catch (error) {
err = error;
succeeded = false;
if (_error.code === 'EEXIST') {
if (err.code === 'EEXIST') {
FS.unlinkSync(absLoc);
try {
FS.symlinkSync(absTarg, absLoc, type);
succeeded = true;
} catch (_error) {}
} catch (error) {}
}
if (!succeeded) {
throw ex;
@ -208,31 +208,22 @@ Definition of the TemplateGenerator class. TODO: Refactor
}
};
/** Freeze newlines for protection against errant JST parsers. */
freeze = function(markup) {
markup.replace(_reg.regN, _defaultOpts.nSym);
return markup.replace(_reg.regR, _defaultOpts.rSym);
};
/** Unfreeze newlines when the coast is clear. */
unfreeze = function(markup) {
markup.replace(_reg.regSymR, '\r');
return markup.replace(_reg.regSymN, '\n');
};
/** Default template generator options. */
_defaultOpts = {
engine: 'underscore',
keepBreaks: true,
freezeBreaks: false,
nSym: '&newl;',
rSym: '&retn;',
nSym: '&newl;', // newline entity
rSym: '&retn;', // return entity
template: {
interpolate: /\{\{(.+?)\}\}/g,
escape: /\{\{\=(.+?)\}\}/g,
@ -269,13 +260,12 @@ Definition of the TemplateGenerator class. TODO: Refactor
prettify: {
indent_size: 2,
unformatted: ['em', 'strong', 'a'],
max_char: 80
max_char: 80 // ← See lib/html.js in above-linked repo
}
};
//wrap_line_length: 120, <-- Don't use this
/** Regexes for linebreak preservation. */
_reg = {
regN: new RegExp('\n', 'g'),
regR: new RegExp('\r', 'g'),

View File

@ -1,32 +1,22 @@
(function() {
/**
Definition of the TextGenerator class.
@module generators/text-generator
@license MIT. See LICENSE.md for details.
*/
(function() {
var TemplateGenerator, TextGenerator,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
var TemplateGenerator, TextGenerator;
TemplateGenerator = require('./template-generator');
/**
The TextGenerator generates a plain-text resume via the TemplateGenerator.
*/
module.exports = TextGenerator = (function(superClass) {
extend(TextGenerator, superClass);
function TextGenerator() {
TextGenerator.__super__.constructor.call(this, 'txt');
module.exports = TextGenerator = class TextGenerator extends TemplateGenerator {
constructor() {
super('txt');
}
return TextGenerator;
})(TemplateGenerator);
};
}).call(this);

View File

@ -1,27 +1,19 @@
(function() {
/*
Definition of the WordGenerator class.
@module generators/word-generator
@license MIT. See LICENSE.md for details.
*/
(function() {
var TemplateGenerator, WordGenerator,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
var TemplateGenerator, WordGenerator;
TemplateGenerator = require('./template-generator');
module.exports = WordGenerator = (function(superClass) {
extend(WordGenerator, superClass);
function WordGenerator() {
WordGenerator.__super__.constructor.call(this, 'doc', 'xml');
module.exports = WordGenerator = class WordGenerator extends TemplateGenerator {
constructor() {
super('doc', 'xml');
}
return WordGenerator;
})(TemplateGenerator);
};
}).call(this);

View File

@ -1,30 +1,20 @@
(function() {
/**
Definition of the XMLGenerator class.
@license MIT. See LICENSE.md for details.
@module generatprs/xml-generator
*/
(function() {
var BaseGenerator, XMLGenerator,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
var BaseGenerator, XMLGenerator;
BaseGenerator = require('./base-generator');
/** The XmlGenerator generates an XML resume via the TemplateGenerator. */
module.exports = XMLGenerator = (function(superClass) {
extend(XMLGenerator, superClass);
function XMLGenerator() {
XMLGenerator.__super__.constructor.call(this, 'xml');
module.exports = XMLGenerator = class XMLGenerator extends BaseGenerator {
constructor() {
super('xml');
}
return XMLGenerator;
})(BaseGenerator);
};
}).call(this);

View File

@ -1,32 +1,22 @@
(function() {
/**
Definition of the YAMLGenerator class.
@module yaml-generator.js
@license MIT. See LICENSE.md for details.
*/
(function() {
var TemplateGenerator, YAMLGenerator,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
var TemplateGenerator, YAMLGenerator;
TemplateGenerator = require('./template-generator');
/**
YamlGenerator generates a YAML-formatted resume via TemplateGenerator.
*/
module.exports = YAMLGenerator = (function(superClass) {
extend(YAMLGenerator, superClass);
function YAMLGenerator() {
YAMLGenerator.__super__.constructor.call(this, 'yml', 'yml');
module.exports = YAMLGenerator = class YAMLGenerator extends TemplateGenerator {
constructor() {
super('yml', 'yml');
}
return YAMLGenerator;
})(TemplateGenerator);
};
}).call(this);

View File

@ -1,11 +1,10 @@
(function() {
/**
Block helper definitions for HackMyResume / FluentCV.
@license MIT. See LICENSE.md for details.
@module helpers/generic-helpers
*/
(function() {
/** Block helper function definitions. */
var BlockHelpers, HMSTATUS, LO, _, unused;
HMSTATUS = require('../core/status-codes');
@ -16,11 +15,7 @@ Block helper definitions for HackMyResume / FluentCV.
unused = require('../utils/string');
/** Block helper function definitions. */
BlockHelpers = module.exports = {
/**
Emit the enclosed content if the resume has a section with
the specified name. Otherwise, emit an empty string ''.
@ -53,7 +48,6 @@ Block helper definitions for HackMyResume / FluentCV.
return options.fn(this);
}
},
/**
Emit the enclosed content if the resume has the named
property or subproperty.
@ -64,7 +58,6 @@ Block helper definitions for HackMyResume / FluentCV.
return options.fn(this);
}
},
/**
Return true if either value is truthy.
@method either

View File

@ -1,11 +1,9 @@
(function() {
/**
Generic template helper definitions for command-line output.
@module console-helpers.js
@license MIT. See LICENSE.md for details.
*/
(function() {
var CHALK, LO, PAD, _, consoleFormatHelpers;
PAD = require('string-padding');
@ -21,7 +19,7 @@ Generic template helper definitions for command-line output.
consoleFormatHelpers = module.exports = {
v: function(val, defaultVal, padding, style) {
var retVal, spaces;
retVal = val === null || val === void 0 ? defaultVal : val;
retVal = (val === null || val === void 0) ? defaultVal : val;
spaces = 0;
if (String.is(padding)) {
spaces = parseInt(padding, 10);

View File

@ -1,11 +1,17 @@
(function() {
/**
Generic template helper definitions for HackMyResume / FluentCV.
@license MIT. See LICENSE.md for details.
@module helpers/generic-helpers
*/
(function() {
/** Generic template helper function definitions. */
/**
Format a from/to date range for display.
*/
/**
Report an error to the outside world without throwing an exception. Currently
relies on kludging the running verb into. opts.
*/
var FS, FluentDate, GenericHelpers, H2W, HMSTATUS, LO, MD, PATH, XML, _, _fromTo, _reportError, _skillLevelToIndex, moment, printf, unused;
MD = require('marked');
@ -32,11 +38,7 @@ Generic template helper definitions for HackMyResume / FluentCV.
unused = require('../utils/string');
/** Generic template helper function definitions. */
GenericHelpers = module.exports = {
/**
Emit a formatted string representing the specified datetime.
Convert the input date to the specified format through Moment.js. If date is
@ -58,22 +60,32 @@ Generic template helper definitions for HackMyResume / FluentCV.
if (dtFormat == null) {
dtFormat = 'YYYY-MM';
}
// If a Moment.js object was passed in, just call format on it
if (datetime && moment.isMoment(datetime)) {
return datetime.format(dtFormat);
}
if (String.is(datetime)) {
// If a string was passed in, convert to Moment using the 2-paramter
// constructor with an explicit format string.
momentDate = moment(datetime, dtFormat);
if (momentDate.isValid()) {
return momentDate.format(dtFormat);
}
// If that didn't work, try again with the single-parameter constructor
// but this may throw a deprecation warning
momentDate = moment(datetime);
if (momentDate.isValid()) {
return momentDate.format(dtFormat);
}
}
// We weren't able to format the provided datetime. Now do one of three
// things.
// 1. If datetime is non-null/non-falsy, return it. For this helper,
// string date values that we can't parse are assumed to be display dates.
// 2. If datetime IS null or falsy, use the value from the fallback.
// 3. If the fallback value is specifically 'true', emit 'Present'.
return datetime || (typeof fallback === 'string' ? fallback : (fallback === true ? 'Present' : ''));
},
/**
Emit a formatted string representing the specified datetime.
@param {string} dateValue A raw date value from the FRESH or JRS resume.
@ -107,7 +119,6 @@ Generic template helper definitions for HackMyResume / FluentCV.
}
return dateValue;
},
/**
Given a resume sub-object with a start/end date, format a representation of
the date range.
@ -118,7 +129,6 @@ Generic template helper definitions for HackMyResume / FluentCV.
}
return _fromTo(obj.start, obj.end, fmt, sep, fallback);
},
/**
Format a from/to date range for display.
@method toFrom
@ -126,7 +136,6 @@ Generic template helper definitions for HackMyResume / FluentCV.
fromTo: function() {
return _fromTo.apply(this, arguments);
},
/**
Return a named color value as an RRGGBB string.
@method toFrom
@ -150,7 +159,6 @@ Generic template helper definitions for HackMyResume / FluentCV.
return ret;
}
},
/**
Emit the size of the specified named font.
@param key {String} A named style from the "fonts" section of the theme's
@ -170,18 +178,22 @@ Generic template helper definitions for HackMyResume / FluentCV.
} else if (GenericHelpers.theme.fonts) {
fontSpec = LO.get(GenericHelpers.theme.fonts, this.format + '.' + key);
if (!fontSpec) {
// Check for an "all" format
if (GenericHelpers.theme.fonts.all) {
fontSpec = GenericHelpers.theme.fonts.all[key];
}
}
if (fontSpec) {
// fontSpec can be a string, an array, or an object
if (String.is(fontSpec)) {
// No font size was specified, only a font family.
} else if (_.isArray(fontSpec)) {
if (!String.is(fontSpec[0])) {
ret = fontSpec[0].size;
}
} else {
// A font description object.
ret = fontSpec.size;
}
}
@ -200,7 +212,6 @@ Generic template helper definitions for HackMyResume / FluentCV.
}
return ret;
},
/**
Emit the font face (such as 'Helvetica' or 'Calibri') associated with the
provided key.
@ -220,19 +231,25 @@ Generic template helper definitions for HackMyResume / FluentCV.
expected: 'key'
});
return ret;
// If the theme has a "fonts" section, lookup the font face.
} else if (GenericHelpers.theme.fonts) {
fontSpec = LO.get(GenericHelpers.theme.fonts, this.format + '.' + key);
if (!fontSpec) {
// Check for an "all" format
if (GenericHelpers.theme.fonts.all) {
fontSpec = GenericHelpers.theme.fonts.all[key];
}
}
if (fontSpec) {
// fontSpec can be a string, an array, or an object
if (String.is(fontSpec)) {
ret = fontSpec;
} else if (_.isArray(fontSpec)) {
// An array of fonts were specified. Each one could be a string
// or an object
ret = String.is(fontSpec[0]) ? fontSpec[0] : fontSpec[0].name;
} else {
// A font description object.
ret = fontSpec.name;
}
}
@ -250,18 +267,6 @@ Generic template helper definitions for HackMyResume / FluentCV.
}
return ret;
},
/**
Emit a comma-delimited list of font names suitable associated with the
provided key.
@param key {String} A named style from the "fonts" section of the theme's
theme.json file. For example: 'default' or 'heading1'.
@param defFontList {Array} The font list to use if the specified key isn't
present. Can be an array of valid font-face name such as 'Helvetica Neue'
or 'Calibri'.
@param sep {String} The default separator to use in the rendered output.
Defaults to ", " (comma with a space).
*/
fontList: function(key, defFontList, sep) {
var fontSpec, hasDef, ret;
ret = '';
@ -280,14 +285,18 @@ Generic template helper definitions for HackMyResume / FluentCV.
}
}
if (fontSpec) {
// fontSpec can be a string, an array, or an object
if (String.is(fontSpec)) {
ret = fontSpec;
} else if (_.isArray(fontSpec)) {
// An array of fonts were specified. Each one could be a string
// or an object
fontSpec = fontSpec.map(function(ff) {
return "'" + (String.is(ff) ? ff : ff.name) + "'";
});
ret = fontSpec.join(sep === void 0 ? ', ' : sep || '');
} else {
// A font description object.
ret = fontSpec.name;
}
}
@ -306,11 +315,6 @@ Generic template helper definitions for HackMyResume / FluentCV.
}
return ret;
},
/**
Capitalize the first letter of the word. TODO: Rename
@method section
*/
camelCase: function(val) {
val = (val && val.trim()) || '';
if (val) {
@ -319,7 +323,6 @@ Generic template helper definitions for HackMyResume / FluentCV.
return val;
}
},
/**
Display a user-overridable section title for a FRESH resume theme. Use this in
lieue of hard-coding section titles.
@ -341,11 +344,14 @@ Generic template helper definitions for HackMyResume / FluentCV.
@method sectionTitle
*/
sectionTitle: function(sname, stitle) {
// If not provided by the user, stitle should default to sname. ps.
// Handlebars silently passes in the options object to the last param,
// where in Underscore stitle will be null/undefined, so we check both.
// TODO: not actually sure that's true, given that we _.wrap these functions
stitle = (stitle && String.is(stitle) && stitle) || sname;
// If there's a section title override, use it.
return (this.opts.stitles && this.opts.stitles[sname.toLowerCase().trim()]) || stitle;
},
/** Convert inline Markdown to inline WordProcessingML. */
wpml: function(txt, inline) {
if (!txt) {
return '';
@ -356,7 +362,6 @@ Generic template helper definitions for HackMyResume / FluentCV.
txt = H2W(txt);
return txt;
},
/**
Emit a conditional link.
@method link
@ -368,7 +373,6 @@ Generic template helper definitions for HackMyResume / FluentCV.
return text;
}
},
/**
Emit a conditional Markdown link.
@method link
@ -380,7 +384,6 @@ Generic template helper definitions for HackMyResume / FluentCV.
return text;
}
},
/**
Return the last word of the specified text.
@method lastWord
@ -392,7 +395,6 @@ Generic template helper definitions for HackMyResume / FluentCV.
return '';
}
},
/**
Convert a skill level to an RGB color triplet. TODO: refactor
@method skillColor
@ -407,7 +409,6 @@ Generic template helper definitions for HackMyResume / FluentCV.
skillColors = (this.theme && this.theme.palette && this.theme.palette.skillLevels) || ['#FFFFFF', '#5CB85C', '#F1C40F', '#428BCA', '#C00000'];
return skillColors[idx];
},
/**
Return an appropriate height. TODO: refactor
@method lastWord
@ -417,7 +418,6 @@ Generic template helper definitions for HackMyResume / FluentCV.
idx = _skillLevelToIndex(lvl);
return ['38.25', '30', '16', '8', '0'][idx];
},
/**
Return all but the last word of the input text.
@method initialWords
@ -429,7 +429,6 @@ Generic template helper definitions for HackMyResume / FluentCV.
return '';
}
},
/**
Trim the protocol (http or https) from a URL/
@method trimURL
@ -441,7 +440,6 @@ Generic template helper definitions for HackMyResume / FluentCV.
return '';
}
},
/**
Convert text to lowercase.
@method toLower
@ -453,7 +451,6 @@ Generic template helper definitions for HackMyResume / FluentCV.
return '';
}
},
/**
Convert text to lowercase.
@method toLower
@ -465,7 +462,6 @@ Generic template helper definitions for HackMyResume / FluentCV.
return '';
}
},
/**
Conditional stylesheet link. Creates a link to the specified stylesheet with
<link> or embeds the styles inline with <style></style>, depending on the
@ -477,6 +473,7 @@ Generic template helper definitions for HackMyResume / FluentCV.
*/
styleSheet: function(url, linkage) {
var rawCss, renderedCss, ret;
// Establish the linkage style
linkage = this.opts.css || linkage || 'embed';
ret = '';
if (linkage === 'link') {
@ -486,12 +483,15 @@ Generic template helper definitions for HackMyResume / FluentCV.
renderedCss = this.engine.generateSimple(this, rawCss);
ret = printf('<style>%s</style>', renderedCss);
}
// If the currently-executing template is inherited, append styles
if (this.opts.themeObj.inherits && this.opts.themeObj.inherits.html && this.format === 'html') {
ret += linkage === 'link' ? '<link href="' + this.opts.themeObj.overrides.path + '" rel="stylesheet" type="text/css">' : '<style>' + this.opts.themeObj.overrides.data + '</style>';
}
// TODO: It would be nice to use Handlebar.SafeString here, but these
// are supposed to be generic helpers. Provide an equivalent, or expose
// it when Handlebars is the chosen engine, which is most of the time.
return ret;
},
/**
Perform a generic comparison.
See: http://doginthehat.com.au/2012/02/comparison-block-helper-for-handlebars-templates
@ -539,7 +539,6 @@ Generic template helper definitions for HackMyResume / FluentCV.
return options.inverse(this);
}
},
/**
Emit padded text.
*/
@ -558,7 +557,6 @@ Generic template helper definitions for HackMyResume / FluentCV.
}
return ret;
},
/**
Given the name of a skill ("JavaScript" or "HVAC repair"), return the number
of years assigned to that skill in the resume.skills.list collection.
@ -574,7 +572,6 @@ Generic template helper definitions for HackMyResume / FluentCV.
return '?';
}
},
/**
Given an object that may be a string or an object, return it as-is if it's a
string, otherwise return the value at obj[objPath].
@ -588,23 +585,14 @@ Generic template helper definitions for HackMyResume / FluentCV.
}
};
/**
Report an error to the outside world without throwing an exception. Currently
relies on kludging the running verb into. opts.
*/
_reportError = function(code, params) {
return GenericHelpers.opts.errHandler.err(code, params);
};
/**
Format a from/to date range for display.
*/
_fromTo = function(dateA, dateB, fmt, sep, fallback) {
var dateATrim, dateBTrim, dateFrom, dateTemp, dateTo, reserved;
// Prevent accidental use of safe.start, safe.end, safe.date
// The dateRange helper is for raw dates only
if (moment.isMoment(dateA) || moment.isMoment(dateB)) {
_reportError(HMSTATUS.invalidHelperUse, {
helper: 'dateRange'
@ -614,6 +602,7 @@ Generic template helper definitions for HackMyResume / FluentCV.
dateFrom = null;
dateTo = null;
dateTemp = null;
// Check for 'current', 'present', 'now', '', null, and undefined
dateA = dateA || '';
dateB = dateB || '';
dateATrim = dateA.trim().toLowerCase();
@ -674,6 +663,25 @@ Generic template helper definitions for HackMyResume / FluentCV.
return idx;
};
// Note [1] --------------------------------------------------------------------
// Make sure it's precisely a string or array since some template engines jam
// their options/context object into the last parameter and we are allowing the
// defFont parameter to be omitted in certain cases. This is a little kludgy,
// but works fine for this case. If we start doing this regularly, we should
// rebind these parameters.
// Note [2]: -------------------------------------------------------------------
// If execution reaches here, some sort of cosmic ray or sunspot has landed on
// HackMyResume, or a theme author is deliberately messing with us by doing
// something like:
// "fonts": {
// "default": "",
// "heading1": null
// }
// Rather than sort it out, we'll just fall back to defFont.
}).call(this);
//# sourceMappingURL=generic-helpers.js.map

View File

@ -1,11 +1,9 @@
(function() {
/**
Template helper definitions for Handlebars.
@license MIT. See LICENSE.md for details.
@module handlebars-helpers.js
*/
(function() {
var HANDLEBARS, HMS, _, blockHelpers, helpers, path;
HANDLEBARS = require('handlebars');
@ -20,32 +18,38 @@ Template helper definitions for Handlebars.
HMS = require('../core/status-codes');
/**
Register useful Handlebars helpers.
@method registerHelpers
*/
module.exports = function(theme, rez, opts) {
var curGlob, ex, glob, slash, wrappedHelpers;
helpers.theme = theme;
helpers.opts = opts;
helpers.type = 'handlebars';
// Prepare generic helpers for use with Handlebars. We do this by wrapping them
// in a Handlebars-aware wrapper which calls the helper internally.
wrappedHelpers = _.mapObject(helpers, function(hVal, hKey) {
if (_.isFunction(hVal)) {
return _.wrap(hVal, function(func) {
var args;
args = Array.prototype.slice.call(arguments);
args.shift();
args[args.length - 1] = rez;
return func.apply(this, args);
args.shift(); // lose the 1st element (func) [^1]
//args.pop() # lose the last element (HB options hash)
args[args.length - 1] = rez; // replace w/ resume object
return func.apply(this, args); // call the generic helper
});
}
return hVal;
}, this);
HANDLEBARS.registerHelper(wrappedHelpers);
// Prepare Handlebars-specific helpers - "blockHelpers" is really a misnomer
// since any kind of Handlebars-specific helper can live here
HANDLEBARS.registerHelper(blockHelpers);
if (_.isString(theme.helpers)) {
// Register any theme-provided custom helpers...
// Normalize "theme.helpers" (string or array) to an array
theme.helpers = [theme.helpers];
}
if (_.isArray(theme.helpers)) {
@ -53,14 +57,14 @@ Template helper definitions for Handlebars.
slash = require('slash');
curGlob = null;
try {
_.each(theme.helpers, function(fGlob) {
_.each(theme.helpers, function(fGlob) { // foreach theme.helpers entry
var files;
curGlob = fGlob;
fGlob = path.join(theme.folder, fGlob);
files = glob.sync(slash(fGlob));
if (files.length > 0) {
_.each(files, function(f) {
HANDLEBARS.registerHelper(require(f));
curGlob = fGlob; // ..cache in case of exception
fGlob = path.join(theme.folder, fGlob); // ..make relative to theme
files = glob.sync(slash(fGlob)); // ..expand the glob
if (files.length > 0) { // ..guard against empty glob
_.each(files, function(f) { // ..loop over concrete paths
HANDLEBARS.registerHelper(require(f)); // ..register the path
});
} else {
throw {
@ -70,8 +74,8 @@ Template helper definitions for Handlebars.
};
}
});
} catch (_error) {
ex = _error;
} catch (error) {
ex = error;
throw {
fluenterror: HMS.themeHelperLoad,
inner: ex,
@ -82,6 +86,12 @@ Template helper definitions for Handlebars.
}
};
// [^1]: This little bit of acrobatics ensures that our generic helpers are
// called as generic helpers, not as Handlebars-specific helpers. This allows
// them to be used in other templating engines, like Underscore. If you need a
// Handlebars-specific helper with normal Handlebars context and options, put it
// in block-helpers.coffee.
}).call(this);
//# sourceMappingURL=handlebars-helpers.js.map

View File

@ -1,11 +1,9 @@
(function() {
/**
Template helper definitions for Underscore.
@license MIT. See LICENSE.md for details.
@module handlebars-helpers.js
*/
(function() {
var HANDLEBARS, _, helpers;
HANDLEBARS = require('handlebars');
@ -14,12 +12,10 @@ Template helper definitions for Underscore.
helpers = require('./generic-helpers');
/**
Register useful Underscore helpers.
@method registerHelpers
*/
module.exports = function(theme, opts, cssInfo, ctx, eng) {
helpers.theme = theme;
helpers.opts = opts;

8
dist/index.js vendored
View File

@ -1,21 +1,17 @@
(function() {
/**
External API surface for HackMyResume.
@license MIT. See LICENSE.md for details.
@module hackmycore/index
*/
/** API facade for HackMyResume. */
(function() {
module.exports = {
verbs: {
build: require('./verbs/build'),
analyze: require('./verbs/analyze'),
validate: require('./verbs/validate'),
convert: require('./verbs/convert'),
"new": require('./verbs/create'),
new: require('./verbs/create'),
peek: require('./verbs/peek')
},
alias: {

View File

@ -8,7 +8,6 @@
lo = require('lodash');
module.exports = {
/**
Compute the total duration of the work history.
@returns The total duration of the sheet's work history, that is, the number
@ -23,10 +22,16 @@
if (!hist || !hist.length) {
return 0;
}
// BEGIN CODE DUPLICATION --> src/inspectors/gap-inspector.coffee (TODO)
// Convert the candidate's employment history to an array of dates,
// where each element in the array is a start date or an end date of a
// job -- it doesn't matter which.
new_e = hist.map(function(job) {
var obj;
obj = _.pick(job, [startKey, endKey]);
if (!_.has(obj, endKey)) {
// Synthesize an end date if this is a "current" gig
obj[endKey] = 'current';
}
if (obj && (obj[startKey] || obj[endKey])) {
@ -38,6 +43,7 @@
}
return obj;
});
// Flatten the array, remove empties, and sort
new_e = _.filter(_.flatten(new_e, true), function(v) {
return v && v.length && v[0] && v[0].length;
});
@ -47,6 +53,7 @@
new_e = _.sortBy(new_e, function(elem) {
return elem[1].unix();
});
// END CODE DUPLICATION
firstDate = _.first(new_e)[1];
lastDate = _.last(new_e)[1];
return lastDate.diff(firstDate, unit);

View File

@ -1,11 +1,12 @@
(function() {
/**
Employment gap analysis for HackMyResume.
@license MIT. See LICENSE.md for details.
@module inspectors/gap-inspector
*/
(function() {
/**
Identify gaps in the candidate's employment history.
*/
var FluentDate, LO, _, gapInspector, moment;
_ = require('underscore');
@ -16,14 +17,8 @@ Employment gap analysis for HackMyResume.
LO = require('lodash');
/**
Identify gaps in the candidate's employment history.
*/
gapInspector = module.exports = {
moniker: 'gap-inspector',
/**
Run the Gap Analyzer on a resume.
@method run
@ -38,6 +33,7 @@ Employment gap analysis for HackMyResume.
*/
run: function(rez) {
var coverage, dur, g, gap_start, hist, new_e, num_gaps, o, ref_count, tdur, total_gap_days;
// This is what we'll return
coverage = {
gaps: [],
overlaps: [],
@ -48,10 +44,14 @@ Employment gap analysis for HackMyResume.
gaps: 0
}
};
// Missing employment section? Bye bye.
hist = LO.get(rez, 'employment.history');
if (!hist || !hist.length) {
return coverage;
}
// Convert the candidate's employment history to an array of dates,
// where each element in the array is a start date or an end date of a
// job -- it doesn't matter which.
new_e = hist.map(function(job) {
var obj;
obj = _.pick(job, ['start', 'end']);
@ -64,6 +64,7 @@ Employment gap analysis for HackMyResume.
}
return obj;
});
// Flatten the array, remove empties, and sort
new_e = _.filter(_.flatten(new_e, true), function(v) {
return v && v.length && v[0] && v[0].length;
});
@ -73,6 +74,11 @@ Employment gap analysis for HackMyResume.
new_e = _.sortBy(new_e, function(elem) {
return elem[1].unix();
});
// Iterate over elements in the array. Each time a start date is found,
// increment a reference count. Each time an end date is found, decrement
// the reference count. When the reference count reaches 0, we have a gap.
// When the reference count is > 0, the candidate is employed. When the
// reference count reaches 2, the candidate is overlapped.
num_gaps = 0;
ref_count = 0;
total_gap_days = 0;
@ -81,11 +87,13 @@ Employment gap analysis for HackMyResume.
var inc, lastGap, lastOver;
inc = point[0] === 'start' ? 1 : -1;
ref_count += inc;
// If the ref count just reached 0, start a new GAP
if (ref_count === 0) {
return coverage.gaps.push({
start: point[1],
end: null
});
// If the ref count reached 1 by rising, end the last GAP
} else if (ref_count === 1 && inc === 1) {
lastGap = _.last(coverage.gaps);
if (lastGap) {
@ -93,11 +101,13 @@ Employment gap analysis for HackMyResume.
lastGap.duration = lastGap.end.diff(lastGap.start, 'days');
return total_gap_days += lastGap.duration;
}
// If the ref count reaches 2 by rising, start a new OVERLAP
} else if (ref_count === 2 && inc === 1) {
return coverage.overlaps.push({
start: point[1],
end: null
});
// If the ref count reaches 1 by falling, end the last OVERLAP
} else if (ref_count === 1 && inc === -1) {
lastOver = _.last(coverage.overlaps);
if (lastOver) {
@ -109,6 +119,9 @@ Employment gap analysis for HackMyResume.
}
}
});
// It's possible that the last gap/overlap didn't have an explicit .end
// date.If so, set the end date to the present date and compute the
// duration normally.
if (coverage.overlaps.length) {
o = _.last(coverage.overlaps);
if (o && !o.end) {
@ -123,6 +136,7 @@ Employment gap analysis for HackMyResume.
g.duration = g.end.diff(g.start, 'days');
}
}
// Package data for return to the client
tdur = rez.duration('days');
dur = {
total: tdur,

View File

@ -1,30 +1,24 @@
(function() {
/**
Keyword analysis for HackMyResume.
@license MIT. See LICENSE.md for details.
@module inspectors/keyword-inspector
*/
(function() {
var FluentDate, _, keywordInspector;
_ = require('underscore');
FluentDate = require('../core/fluent-date');
/**
Analyze the resume's use of keywords.
TODO: BUG: Keyword search regex is inaccurate, especially for one or two
letter keywords like "C" or "CLI".
@class keywordInspector
*/
var FluentDate, _, keywordInspector;
_ = require('underscore');
FluentDate = require('../core/fluent-date');
keywordInspector = module.exports = {
/** A unique name for this inspector. */
moniker: 'keyword-inspector',
/**
Run the Keyword Inspector on a resume.
@method run
@ -32,17 +26,38 @@ Keyword analysis for HackMyResume.
*/
run: function(rez) {
var prefix, regex_quote, searchable, suffix;
// "Quote" or safely escape a keyword so it can be used as a regex. For
// example, if the keyword is "C++", yield "C\+\+".
// http://stackoverflow.com/a/2593661/4942583
regex_quote = function(str) {
return (str + '').replace(/[.?*+^$[\]\\(){}|-]/ig, "\\$&");
};
// Create a searchable plain-text digest of the resume
// TODO: BUG: Don't search within keywords for other keywords. Job A
// declares the "foo" keyword. Job B declares the "foo & bar" keyword. Job
// B's mention of "foobar" should not count as a mention of "foo".
// To achieve this, remove keywords from the search digest and treat them
// separately.
searchable = '';
rez.transformStrings(['imp', 'computed', 'safe'], function(key, val) {
return searchable += ' ' + val;
});
// Assemble a regex skeleton we can use to test for keywords with a bit
// more
prefix = '(?:' + ['^', '\\s+', '[\\.,]+'].join('|') + ')';
suffix = '(?:' + ['$', '\\s+', '[\\.,]+'].join('|') + ')';
return rez.keywords().map(function(kw) {
var count, myArray, regex, regex_str;
// 1. Using word boundary or other regex class is inaccurate
// var regex = new RegExp( '\\b' + regex_quote( kw )/* + '\\b'*/, 'ig');
// 2. Searching for the raw keyword is inaccurate ("C" will match any
// word containing a 'c'!).
// var regex = new RegExp( regex_quote( kw ), 'ig');
// 3. Instead, use a custom regex with special delimeters.
regex_str = prefix + regex_quote(kw) + suffix;
regex = new RegExp(regex_str, 'ig');
myArray = null;

View File

@ -1,26 +1,21 @@
(function() {
/**
Section analysis for HackMyResume.
@license MIT. See LICENSE.md for details.
@module inspectors/totals-inspector
*/
(function() {
/**
Retrieve sectional overview and summary information.
@class totalsInspector
*/
var FluentDate, _, totalsInspector;
_ = require('underscore');
FluentDate = require('../core/fluent-date');
/**
Retrieve sectional overview and summary information.
@class totalsInspector
*/
totalsInspector = module.exports = {
moniker: 'totals-inspector',
/**
Run the Totals Inspector on a resume.
@method run

View File

@ -1,11 +1,13 @@
(function() {
/**
Definition of the HandlebarsGenerator class.
@license MIT. See LICENSE.md for details.
@module renderers/handlebars-generator
*/
(function() {
/**
Perform template-based resume generation using Handlebars.js.
@class HandlebarsGenerator
*/
var FS, HANDLEBARS, HMSTATUS, HandlebarsGenerator, PATH, READFILES, SLASH, _, parsePath, registerHelpers, registerPartials;
_ = require('underscore');
@ -26,31 +28,28 @@ Definition of the HandlebarsGenerator class.
SLASH = require('slash');
/**
Perform template-based resume generation using Handlebars.js.
@class HandlebarsGenerator
*/
HandlebarsGenerator = module.exports = {
generateSimple: function(data, tpl) {
var template;
var err, template;
try {
// Compile and run the Handlebars template.
template = HANDLEBARS.compile(tpl, {
strict: false,
assumeObjects: false,
noEscape: data.opts.noescape
});
return template(data);
} catch (_error) {
} catch (error1) {
err = error1;
throw {
fluenterror: HMSTATUS[template ? 'invokeTemplate' : 'compileTemplate'],
inner: _error
inner: err
};
}
},
generate: function(json, jst, format, curFmt, opts, theme) {
var ctx, encData;
// Preprocess text
encData = json;
if (format === 'html' || format === 'pdf') {
encData = json.markdownify();
@ -58,8 +57,10 @@ Definition of the HandlebarsGenerator class.
if (format === 'doc') {
encData = json.xmlify();
}
// Set up partials and helpers
registerPartials(format, theme);
registerHelpers(theme, encData, opts);
// Set up the context
ctx = {
r: encData,
RAW: json,
@ -70,6 +71,7 @@ Definition of the HandlebarsGenerator class.
results: curFmt.files,
headFragment: opts.headFragment || ''
};
// Render the template
return this.generateSimple(ctx, jst);
}
};
@ -77,7 +79,10 @@ Definition of the HandlebarsGenerator class.
registerPartials = function(format, theme) {
var partialsFolder;
if (_.contains(['html', 'doc', 'md', 'txt', 'pdf'], format)) {
// Locate the global partials folder
partialsFolder = PATH.join(parsePath(require.resolve('fresh-themes')).dirname, '/partials/', format === 'pdf' ? 'html' : format);
// Register global partials in the /partials/[format] folder
// TODO: Only do this once per HMR invocation.
_.each(READFILES(partialsFolder, function(error) {
return {};
}), function(el) {
@ -90,6 +95,7 @@ Definition of the HandlebarsGenerator class.
return theme.partialsInitialized = true;
});
}
// Register theme-specific partials
return _.each(theme.partials, function(el) {
var compiledTemplate, tplData;
tplData = FS.readFileSync(el.path, 'utf8');

View File

@ -1,11 +1,13 @@
(function() {
/**
Definition of the JRSGenerator class.
@license MIT. See LICENSE.md for details.
@module renderers/jrs-generator
*/
(function() {
/**
Perform template-based resume generation for JSON Resume themes.
@class JRSGenerator
*/
var FS, HANDLEBARS, JRSGenerator, MD, MDIN, PATH, READFILES, SLASH, _, parsePath, registerHelpers;
_ = require('underscore');
@ -26,15 +28,10 @@ Definition of the JRSGenerator class.
MD = require('marked');
/**
Perform template-based resume generation for JSON Resume themes.
@class JRSGenerator
*/
JRSGenerator = module.exports = {
generate: function(json, jst, format, cssInfo, opts, theme) {
var org, rezHtml, turnoff;
// Disable JRS theme chatter (console.log, console.error, etc.)
turnoff = ['log', 'error', 'dir'];
org = turnoff.map(function(c) {
var ret;
@ -42,17 +39,20 @@ Definition of the JRSGenerator class.
console[c] = function() {};
return ret;
});
// Freeze and render
rezHtml = theme.render(json.harden());
// Turn logging back on
turnoff.forEach(function(c, idx) {
return console[c] = org[idx];
});
// Unfreeze and apply Markdown
return rezHtml = rezHtml.replace(/@@@@~[\s\S]*?~@@@@/g, function(val) {
return MDIN(val.replace(/~@@@@/g, '').replace(/@@@@~/g, ''));
});
}
};
MDIN = function(txt) {
MDIN = function(txt) { // TODO: Move this
return MD(txt || '').replace(/^\s*<p>|<\/p>\s*$/gi, '');
};

View File

@ -1,11 +1,13 @@
(function() {
/**
Definition of the UnderscoreGenerator class.
@license MIT. See LICENSE.md for details.
@module underscore-generator.js
*/
(function() {
/**
Perform template-based resume generation using Underscore.js.
@class UnderscoreGenerator
*/
var UnderscoreGenerator, _, escapeLaTeX, registerHelpers;
_ = require('underscore');
@ -16,28 +18,26 @@ Definition of the UnderscoreGenerator class.
escapeLaTeX = require('escape-latex');
/**
Perform template-based resume generation using Underscore.js.
@class UnderscoreGenerator
*/
UnderscoreGenerator = module.exports = {
generateSimple: function(data, tpl) {
var HMS, t;
var HMS, err, t;
try {
// Compile and run the Handlebars template.
t = _.template(tpl);
return t(data);
} catch (_error) {
} catch (error) {
err = error;
//console.dir _error
HMS = require('../core/status-codes');
throw {
fluenterror: HMS[t ? 'invokeTemplate' : 'compileTemplate'],
inner: _error
inner: err
};
}
},
generate: function(json, jst, format, cssInfo, opts, theme) {
var ctx, delims, r, traverse;
// Tweak underscore's default template delimeters
delims = (opts.themeObj && opts.themeObj.delimeters) || opts.template;
if (opts.themeObj && opts.themeObj.delimeters) {
delims = _.mapObject(delims, function(val, key) {
@ -68,16 +68,20 @@ Definition of the UnderscoreGenerator class.
default:
r = json;
}
// Set up the context
ctx = {
r: r,
filt: opts.filters,
XML: require('xml-escape'),
RAW: json,
cssInfo: cssInfo,
//engine: @
headFragment: opts.headFragment || '',
opts: opts
};
// Link to our helpers
registerHelpers(theme, opts, cssInfo, ctx, this);
// Generate!
return this.generateSimple(ctx, jst);
}
};

View File

@ -1,10 +1,8 @@
(function() {
/**
Definition of the SyntaxErrorEx class.
@module file-contains.js
*/
(function() {
module.exports = function(file, needle) {
return require('fs').readFileSync(file, 'utf-8').indexOf(needle) > -1;
};

View File

@ -1,10 +1,23 @@
(function() {
/**
Defines a regex suitable for matching FRESH versions.
@module file-contains.js
*/
// Set up a regex that matches all of the following:
(function() {
// - FRESH
// - JRS
// - FRESCA
// - FRESH@1.0.0
// - FRESH@1.0
// - FRESH@1
// - JRS@0.16.0
// - JRS@0.16
// - JRS@0
// Don't use a SEMVER regex (eg, NPM's semver-regex) because a) we want to
// support partial semvers like "0" or "1.2" and b) we'll expand this later to
// support fully scoped FRESH versions.
module.exports = function() {
return RegExp('^(FRESH|FRESCA|JRS)(?:@(\\d+(?:\\.\\d+)?(?:\\.\\d+)?))?$');
};

View File

@ -1,11 +1,9 @@
(function() {
/**
Definition of the Markdown to WordProcessingML conversion routine.
@license MIT. Copyright (c) 2015 James Devlin / FluentDesk.
@module utils/html-to-wpml
*/
(function() {
var HTML5Tokenizer, XML, _;
XML = require('xml-escape');
@ -16,8 +14,12 @@ Definition of the Markdown to WordProcessingML conversion routine.
module.exports = function(html) {
var final, is_bold, is_italic, is_link, link_url, tokens;
// Tokenize the HTML stream.
tokens = HTML5Tokenizer.tokenize(html);
final = is_bold = is_italic = is_link = link_url = '';
// Process <em>, <strong>, and <a> elements in the HTML stream, producing
// equivalent WordProcessingML that can be dumped into a <w:p> or other
// text container element.
_.each(tokens, function(tok) {
var style;
switch (tok.type) {

View File

@ -1,11 +1,9 @@
(function() {
/**
Inline Markdown-to-Chalk conversion routines.
@license MIT. See LICENSE.md for details.
@module utils/md2chalk
*/
(function() {
var CHALK, LO, MD;
MD = require('marked');

View File

@ -1,4 +1,7 @@
(function() {
// Exemplar script for generating documents with Phantom.js.
// https://raw.githubusercontent.com/ariya/phantomjs/master/examples/rasterize.js
// Converted to CoffeeScript by hacksalot
"use strict";
var address, output, page, pageHeight, pageWidth, size, system;
@ -50,7 +53,7 @@
} else {
console.log("size:", system.args[3]);
pageWidth = parseInt(system.args[3], 10);
pageHeight = parseInt(pageWidth * 3 / 4, 10);
pageHeight = parseInt(pageWidth * 3 / 4, 10); // it's as good an assumption as any
console.log("pageHeight:", pageHeight);
page.viewportSize = {
width: pageWidth,

View File

@ -1,13 +1,11 @@
(function() {
/**
Definition of the ResumeDetector class.
@module utils/resume-detector
@license MIT. See LICENSE.md for details.
*/
(function() {
module.exports = function(rez) {
if (rez.meta && rez.meta.format) {
if (rez.meta && rez.meta.format) { //&& rez.meta.format.substr(0, 5).toUpperCase() == 'FRESH'
return 'fresh';
} else if (rez.basics) {
return 'jrs';

View File

@ -1,6 +1,5 @@
(function() {
module.exports = {
/**
Removes ignored or private fields from a resume object
@returns an object with the following structure:
@ -15,18 +14,18 @@
traverse = require('traverse');
ignoreList = [];
privateList = [];
includePrivates = opts && opts["private"];
scrubbed = traverse(rep).map(function() {
includePrivates = opts && opts.private;
scrubbed = traverse(rep).map(function() { // [^1]
if (!this.isLeaf) {
if (this.node.ignore === true || this.node.ignore === 'true') {
ignoreList.push(this.node);
this["delete"]();
} else if ((this.node["private"] === true || this.node["private"] === 'true') && !includePrivates) {
this.delete();
} else if ((this.node.private === true || this.node.private === 'true') && !includePrivates) {
privateList.push(this.node);
this["delete"]();
this.delete();
}
}
if (_.isArray(this.node)) {
if (_.isArray(this.node)) { // [^2]
this.after(function() {
this.update(_.compact(this.node));
});
@ -40,6 +39,17 @@
}
};
// [^1]: As of v0.6.6, the NPM traverse library has a quirk when attempting
// to remove array elements directly using traverse's `this.remove`. See:
// https://github.com/substack/js-traverse/issues/48
// [^2]: The workaround is to use traverse's 'this.delete' to nullify the value
// first, followed by removal with something like _.compact.
// https://github.com/substack/js-traverse/issues/48#issuecomment-142607200
}).call(this);
//# sourceMappingURL=resume-scrubber.js.map

View File

@ -1,11 +1,9 @@
(function() {
/**
Definition of the SafeJsonLoader class.
@module utils/safe-json-loader
@license MIT. See LICENSE.md for details.
*/
(function() {
var FS, SyntaxErrorEx;
FS = require('fs');
@ -13,16 +11,19 @@ Definition of the SafeJsonLoader class.
SyntaxErrorEx = require('./syntax-error-ex');
module.exports = function(file) {
var ret, retRaw;
var err, ret, retRaw;
ret = {};
try {
ret.raw = FS.readFileSync(file, 'utf8');
ret.json = JSON.parse(ret.raw);
} catch (_error) {
} catch (error) {
err = error;
// If we get here, either FS.readFileSync or JSON.parse failed.
// We'll return HMSTATUS.readError or HMSTATUS.parseError.
retRaw = ret.raw && ret.raw.trim();
ret.ex = {
op: retRaw ? 'parse' : 'read',
inner: SyntaxErrorEx.is(_error) ? new SyntaxErrorEx(_error, retRaw) : _error,
inner: SyntaxErrorEx.is(err) ? new SyntaxErrorEx(err, retRaw) : err,
file: file
};
}

View File

@ -1,19 +1,15 @@
(function() {
/**
Safe spawn utility for HackMyResume / FluentCV.
@module utils/safe-spawn
@license MIT. See LICENSE.md for details.
*/
/** Safely spawn a process synchronously or asynchronously without throwing an
exception
*/
(function() {
exception */
module.exports = function(cmd, args, isSync, callback, param) {
var info, spawn;
var ex, info, spawn;
try {
// .spawnSync not available on earlier Node.js, so default to .spawn
spawn = require('child_process')[isSync ? 'spawnSync' : 'spawn'];
info = spawn(cmd, args);
if (!isSync) {
@ -33,11 +29,12 @@ exception
};
}
}
} catch (_error) {
} catch (error) {
ex = error;
if (typeof callback === "function") {
callback(_error, param);
callback(ex, param);
}
return _error;
return ex;
}
};

View File

@ -1,26 +1,23 @@
(function() {
/**
Object string transformation.
@module utils/string-transformer
@license MIT. See LICENSE.md for details.
*/
(function() {
var _, moment;
_ = require('underscore');
moment = require('moment');
/**
Create a copy of this object in which all string fields have been run through
a transformation function (such as a Markdown filter or XML encoder).
*/
module.exports = function(ret, filt, transformer) {
var that, transformStringsInObject;
that = this;
// TODO: refactor recursion
transformStringsInObject = function(obj, filters) {
if (!obj) {
return;

View File

@ -1,17 +1,13 @@
(function() {
/**
Definitions of string utility functions.
@module utils/string
*/
/**
Determine if the string is null, empty, or whitespace.
See: http://stackoverflow.com/a/32800728/4942583
@method isNullOrWhitespace
*/
(function() {
String.isNullOrWhitespace = function(input) {
return !input || !input.trim();
};

View File

@ -1,10 +1,10 @@
(function() {
/**
Definition of the SyntaxErrorEx class.
@module utils/syntax-error-ex
@license MIT. See LICENSE.md for details.
*/
var SyntaxErrorEx;
/**
Represents a SyntaxError exception with line and column info.
@ -14,13 +14,9 @@ ments, so we reparse on error to grab the line and column.
See: http://stackoverflow.com/q/13323356
@class SyntaxErrorEx
*/
(function() {
var SyntaxErrorEx;
SyntaxErrorEx = (function() {
function SyntaxErrorEx(ex, rawData) {
var JSONLint, colNum, lineNum, lint, ref;
SyntaxErrorEx = class SyntaxErrorEx {
constructor(ex, rawData) {
var JSONLint, colNum, err, lineNum, lint;
lineNum = null;
colNum = null;
JSONLint = require('json-lint');
@ -28,22 +24,22 @@ See: http://stackoverflow.com/q/13323356
comments: false
});
if (lint.error) {
ref = [lint.line, lint.character], this.line = ref[0], this.col = ref[1];
[this.line, this.col] = [lint.line, lint.character];
}
if (!lint.error) {
JSONLint = require('jsonlint');
try {
JSONLint.parse(rawData);
} catch (_error) {
this.line = (/on line (\d+)/.exec(_error))[1];
} catch (error) {
err = error;
this.line = (/on line (\d+)/.exec(err))[1];
}
}
}
return SyntaxErrorEx;
})();
};
// Return true if the supplied parameter is a JavaScript SyntaxError
SyntaxErrorEx.is = function(ex) {
return ex instanceof SyntaxError;
};

32
dist/verbs/analyze.js vendored
View File

@ -1,14 +1,12 @@
(function() {
/**
Implementation of the 'analyze' verb for HackMyResume.
@module verbs/analyze
@license MIT. See LICENSE.md for details.
*/
(function() {
var AnalyzeVerb, HMEVENT, HMSTATUS, MKDIRP, PATH, ResumeFactory, Verb, _, _analyze, _analyzeOne, _loadInspectors, chalk,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
/** Private workhorse for the 'analyze' command. */
/** Analyze a single resume. */
var AnalyzeVerb, HMEVENT, HMSTATUS, MKDIRP, PATH, ResumeFactory, Verb, _, _analyze, _analyzeOne, _loadInspectors, chalk;
MKDIRP = require('mkdirp');
@ -26,22 +24,13 @@ Implementation of the 'analyze' verb for HackMyResume.
chalk = require('chalk');
/** An invokable resume analysis command. */
module.exports = AnalyzeVerb = (function(superClass) {
extend(AnalyzeVerb, superClass);
function AnalyzeVerb() {
AnalyzeVerb.__super__.constructor.call(this, 'analyze', _analyze);
module.exports = AnalyzeVerb = class AnalyzeVerb extends Verb {
constructor() {
super('analyze', _analyze);
}
return AnalyzeVerb;
})(Verb);
/** Private workhorse for the 'analyze' command. */
};
_analyze = function(sources, dst, opts) {
var nlzrs, results;
@ -58,7 +47,7 @@ Implementation of the 'analyze' verb for HackMyResume.
format: 'FRESH',
objectify: true,
inner: {
"private": opts["private"] === true
private: opts.private === true
}
}, this);
if (opts.assert && this.hasError()) {
@ -80,9 +69,6 @@ Implementation of the 'analyze' verb for HackMyResume.
return results;
};
/** Analyze a single resume. */
_analyzeOne = function(resumeObject, nlzrs, opts) {
var info, rez, safeFormat;
rez = resumeObject.rez;

191
dist/verbs/build.js vendored
View File

@ -1,14 +1,49 @@
(function() {
/**
Implementation of the 'build' verb for HackMyResume.
@module verbs/build
@license MIT. See LICENSE.md for details.
*/
(function() {
var BuildVerb, FRESHTheme, FS, HMEVENT, HMSTATUS, JRSTheme, MD, MKDIRP, PATH, RConverter, RTYPES, ResumeFactory, Verb, _, _addFreebieFormats, _build, _err, _expand, _fmts, _loadTheme, _log, _opts, _prep, _rezObj, _single, _verifyOutputs, _verifyTheme, addFreebieFormats, build, expand, extend, loadTheme, parsePath, prep, single, verifyOutputs, verifyTheme,
extend1 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
/**
Reinforce the chosen theme with "freebie" formats provided by HackMyResume.
A "freebie" format is an output format such as JSON, YML, or PNG that can be
generated directly from the resume model or from one of the theme's declared
output formats. For example, the PNG format can be generated for any theme
that declares an HTML format; the theme doesn't have to provide an explicit
PNG template.
@param theTheme A FRESHTheme or JRSTheme object.
*/
/**
Given a source resume in FRESH or JRS format, a destination resume path, and a
theme file, generate 0..N resumes in the desired formats.
@param src Path to the source JSON resume file: "rez/resume.json".
@param dst An array of paths to the target resume file(s).
@param opts Generation options.
*/
/**
Expand output files. For example, "foo.all" should be expanded to
["foo.html", "foo.doc", "foo.pdf", "etc"].
@param dst An array of output files as specified by the user.
@param theTheme A FRESHTheme or JRSTheme object.
*/
/**
Load the specified theme, which could be either a FRESH theme or a JSON Resume
theme (or both).
*/
/**
Prepare for a BUILD run.
*/
/**
Generate a single target resume such as "out/rez.html" or "out/rez.doc".
TODO: Refactor.
@param targInfo Information for the target resume.
@param theme A FRESHTheme or JRSTheme object.
*/
/** Ensure that user-specified outputs/targets are valid. */
/**
Verify the specified theme name/path.
*/
var BuildVerb, FRESHTheme, FS, HMEVENT, HMSTATUS, JRSTheme, MD, MKDIRP, PATH, RConverter, RTYPES, ResumeFactory, Verb, _, _addFreebieFormats, _build, _err, _expand, _fmts, _loadTheme, _log, _opts, _prep, _rezObj, _single, _verifyOutputs, _verifyTheme, addFreebieFormats, build, expand, extend, loadTheme, parsePath, prep, single, verifyOutputs, verifyTheme;
_ = require('underscore');
@ -69,34 +104,17 @@ Implementation of the 'build' verb for HackMyResume.
loadTheme = null;
/** An invokable resume generation command. */
module.exports = BuildVerb = (function(superClass) {
extend1(BuildVerb, superClass);
module.exports = BuildVerb = class BuildVerb extends Verb {
/** Create a new build verb. */
function BuildVerb() {
BuildVerb.__super__.constructor.call(this, 'build', _build);
constructor() {
super('build', _build);
}
return BuildVerb;
})(Verb);
/**
Given a source resume in FRESH or JRS format, a destination resume path, and a
theme file, generate 0..N resumes in the desired formats.
@param src Path to the source JSON resume file: "rez/resume.json".
@param dst An array of paths to the target resume file(s).
@param opts Generation options.
*/
};
_build = function(src, dst, opts) {
var inv, isFRESH, mixed, newEx, orgFormat, problemSheets, results, rez, sheetObjects, sheets, tFolder, targets, theme, toFormat;
var err, inv, isFRESH, mixed, newEx, orgFormat, problemSheets, results, rez, sheetObjects, sheets, tFolder, targets, theme, toFormat;
if (!src || !src.length) {
this.err(HMSTATUS.resumeNotFound, {
quit: true
@ -104,26 +122,30 @@ Implementation of the 'build' verb for HackMyResume.
return null;
}
_prep.call(this, src, dst, opts);
// Load input resumes as JSON...
sheetObjects = ResumeFactory.load(src, {
format: null,
objectify: false,
quit: true,
inner: {
sort: _opts.sort,
"private": _opts["private"]
private: _opts.private
}
}, this);
// Explicit check for any resume loading errors...
problemSheets = _.filter(sheetObjects, function(so) {
return so.fluenterror;
});
if (problemSheets && problemSheets.length) {
problemSheets[0].quit = true;
problemSheets[0].quit = true; // can't go on
this.err(problemSheets[0].fluenterror, problemSheets[0]);
return null;
}
// Get the collection of raw JSON sheets
sheets = sheetObjects.map(function(r) {
return r.json;
});
// Load the theme...
theme = null;
this.stat(HMEVENT.beforeTheme, {
theme: _opts.theme
@ -137,10 +159,11 @@ Implementation of the 'build' verb for HackMyResume.
}
theme = _opts.themeObj = _loadTheme(tFolder);
_addFreebieFormats(theme);
} catch (_error) {
} catch (error) {
err = error;
newEx = {
fluenterror: HMSTATUS.themeLoad,
inner: _error,
inner: err,
attempted: _opts.theme,
quit: true
};
@ -150,6 +173,7 @@ Implementation of the 'build' verb for HackMyResume.
this.stat(HMEVENT.afterTheme, {
theme: theme
});
// Check for invalid outputs...
inv = _verifyOutputs.call(this, dst, theme);
if (inv && inv.length) {
this.err(HMSTATUS.invalidFormat, {
@ -159,6 +183,7 @@ Implementation of the 'build' verb for HackMyResume.
});
return null;
}
//# Merge input resumes, yielding a single source resume...
rez = null;
if (sheets.length > 1) {
isFRESH = !sheets[0].basics;
@ -195,14 +220,17 @@ Implementation of the 'build' verb for HackMyResume.
fmt: toFormat
});
}
// Announce the theme
this.stat(HMEVENT.applyTheme, {
r: rez,
theme: theme
});
// Load the resume into a FRESHResume or JRSResume object
_rezObj = new RTYPES[toFormat]().parseJSON(rez, {
"private": _opts["private"]
private: _opts.private
});
targets = _expand(dst, theme);
// Run the transformation!
_.each(targets, function(t) {
var ref;
if (this.hasError() && opts.assert) {
@ -227,16 +255,12 @@ Implementation of the 'build' verb for HackMyResume.
return results;
};
/**
Prepare for a BUILD run.
*/
_prep = function(src, dst, opts) {
var that;
// Cherry-pick options //_opts = extend( true, _opts, opts );
_opts.theme = (opts.theme && opts.theme.toLowerCase().trim()) || 'modern';
_opts.prettify = opts.prettify === true;
_opts["private"] = opts["private"] === true;
_opts.private = opts.private === true;
_opts.noescape = opts.noescape === true;
_opts.css = opts.css;
_opts.pdf = opts.pdf;
@ -249,6 +273,7 @@ Implementation of the 'build' verb for HackMyResume.
_opts.sort = opts.sort;
_opts.wkhtmltopdf = opts.wkhtmltopdf;
that = this;
// Set up callbacks for internal generators
_opts.onTransform = function(info) {
that.stat(HMEVENT.afterTransform, info);
};
@ -258,17 +283,11 @@ Implementation of the 'build' verb for HackMyResume.
_opts.afterWrite = function(info) {
that.stat(HMEVENT.afterWrite, info);
};
// If two or more files are passed to the GENERATE command and the TO
// keyword is omitted, the last file specifies the output file.
(src.length > 1 && (!dst || !dst.length)) && dst.push(src.pop());
};
/**
Generate a single target resume such as "out/rez.html" or "out/rez.doc".
TODO: Refactor.
@param targInfo Information for the target resume.
@param theme A FRESHTheme or JRSTheme object.
*/
_single = function(targInfo, theme, finished) {
var e, ex, f, fName, fType, outFolder, ret, theFormat;
ret = null;
@ -286,6 +305,8 @@ Implementation of the 'build' verb for HackMyResume.
file: PATH.relative(process.cwd(), f)
});
_opts.targets = finished;
// If targInfo.fmt.files exists, this format is backed by a document.
// Fluent/FRESH themes are handled here.
if (targInfo.fmt.files && targInfo.fmt.files.length) {
theFormat = _fmts.filter(function(fmt) {
return fmt.name === targInfo.fmt.outFormat;
@ -293,15 +314,17 @@ Implementation of the 'build' verb for HackMyResume.
MKDIRP.sync(PATH.dirname(f));
ret = theFormat.gen.generate(_rezObj, f, _opts);
} else {
// Otherwise this is an ad-hoc format (JSON, YML, or PNG) that every theme
// gets "for free".
theFormat = _fmts.filter(function(fmt) {
return fmt.name === targInfo.fmt.outFormat;
})[0];
outFolder = PATH.dirname(f);
MKDIRP.sync(outFolder);
MKDIRP.sync(outFolder); // Ensure dest folder exists;
ret = theFormat.gen.generate(_rezObj, f, _opts);
}
} catch (_error) {
e = _error;
} catch (error) {
e = error;
ex = e;
}
this.stat(HMEVENT.afterGenerate, {
@ -322,9 +345,6 @@ Implementation of the 'build' verb for HackMyResume.
return ret;
};
/** Ensure that user-specified outputs/targets are valid. */
_verifyOutputs = function(targets, theme) {
this.stat(HMEVENT.verifyOutputs, {
targets: targets,
@ -341,18 +361,9 @@ Implementation of the 'build' verb for HackMyResume.
});
};
/**
Reinforce the chosen theme with "freebie" formats provided by HackMyResume.
A "freebie" format is an output format such as JSON, YML, or PNG that can be
generated directly from the resume model or from one of the theme's declared
output formats. For example, the PNG format can be generated for any theme
that declares an HTML format; the theme doesn't have to provide an explicit
PNG template.
@param theTheme A FRESHTheme or JRSTheme object.
*/
_addFreebieFormats = function(theTheme) {
// Add freebie formats (JSON, YAML, PNG) every theme gets...
// Add HTML-driven PNG only if the theme has an HTML format.
theTheme.formats.json = theTheme.formats.json || {
freebie: true,
title: 'json',
@ -383,16 +394,10 @@ Implementation of the 'build' verb for HackMyResume.
}
};
/**
Expand output files. For example, "foo.all" should be expanded to
["foo.html", "foo.doc", "foo.pdf", "etc"].
@param dst An array of output files as specified by the user.
@param theTheme A FRESHTheme or JRSTheme object.
*/
_expand = function(dst, theTheme) {
var destColl, targets;
// Set up the destination collection. It's either the array of files passed
// by the user or 'out/resume.all' if no targets were specified.
destColl = (dst && dst.length && dst) || [PATH.normalize('out/resume.all')];
targets = [];
destColl.forEach(function(t) {
@ -417,19 +422,22 @@ Implementation of the 'build' verb for HackMyResume.
return targets;
};
/**
Verify the specified theme name/path.
*/
_verifyTheme = function(themeNameOrPath) {
var exists, tFolder, themesObj;
// First, see if this is one of the predefined FRESH themes. There are only a
// handful of these, but they may change over time, so we need to query
// the official source of truth: the fresh-themes repository, which mounts the
// themes conveniently by name to the module object, and which is embedded
// locally inside the HackMyResume installation.
themesObj = require('fresh-themes');
if (_.has(themesObj.themes, themeNameOrPath)) {
tFolder = PATH.join(parsePath(require.resolve('fresh-themes')).dirname, '/themes/', themeNameOrPath);
} else {
// Otherwsie it's a path to an arbitrary FRESH or JRS theme sitting somewhere
// on the user's system (or, in the future, at a URI).
tFolder = PATH.resolve(themeNameOrPath);
}
// In either case, make sure the theme folder exists
exists = require('path-exists').sync;
if (exists(tFolder)) {
return tFolder;
@ -441,21 +449,36 @@ Implementation of the 'build' verb for HackMyResume.
}
};
/**
Load the specified theme, which could be either a FRESH theme or a JSON Resume
theme (or both).
*/
_loadTheme = function(tFolder) {
var exists, theTheme, themeJsonPath;
themeJsonPath = PATH.join(tFolder, 'theme.json');
themeJsonPath = PATH.join(tFolder, 'theme.json'); // [^1]
exists = require('path-exists').sync;
// Create a FRESH or JRS theme object
theTheme = exists(themeJsonPath) ? new FRESHTheme().open(tFolder) : new JRSTheme().open(tFolder);
// Cache the theme object
_opts.themeObj = theTheme;
return theTheme;
};
// FOOTNOTES
// ------------------------------------------------------------------------------
// [^1] We don't know ahead of time whether this is a FRESH or JRS theme.
// However, all FRESH themes have a theme.json file, so we'll use that as a
// canary for now, as an interim solution.
// Unfortunately, with the exception of FRESH's theme.json, both FRESH and
// JRS themes are free-form and don't have a ton of reliable distinguishing
// marks, which makes a simple task like ad hoc theme detection harder than
// it should be to do cleanly.
// Another complicating factor is that it's possible for a theme to be BOTH.
// That is, a single set of theme files can serve as a FRESH theme -and- a
// JRS theme.
// TODO: The most robust way to deal with all these issues is with a strong
// theme validator. If a theme structure validates as a particular theme
// type, then for all intents and purposes, it IS a theme of that type.
}).call(this);
//# sourceMappingURL=build.js.map

63
dist/verbs/convert.js vendored
View File

@ -1,14 +1,13 @@
(function() {
/**
Implementation of the 'convert' verb for HackMyResume.
@module verbs/convert
@license MIT. See LICENSE.md for details.
*/
(function() {
var ConvertVerb, HMEVENT, HMSTATUS, ResumeFactory, Verb, _, _convert, _convertOne, chalk,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
/** Private workhorse method. Convert 0..N resumes between FRESH and JRS
formats. */
/** Private workhorse method. Convert a single resume. */
var ConvertVerb, HMEVENT, HMSTATUS, ResumeFactory, Verb, _, _convert, _convertOne, chalk;
ResumeFactory = require('../core/resume-factory');
@ -22,21 +21,12 @@ Implementation of the 'convert' verb for HackMyResume.
HMEVENT = require('../core/event-codes');
module.exports = ConvertVerb = (function(superClass) {
extend(ConvertVerb, superClass);
function ConvertVerb() {
ConvertVerb.__super__.constructor.call(this, 'convert', _convert);
module.exports = ConvertVerb = class ConvertVerb extends Verb {
constructor() {
super('convert', _convert);
}
return ConvertVerb;
})(Verb);
/** Private workhorse method. Convert 0..N resumes between FRESH and JRS
formats.
*/
};
_convert = function(srcs, dst, opts) {
var fmtUp, results, targetVer;
@ -60,11 +50,13 @@ Implementation of the 'convert' verb for HackMyResume.
});
}
}
// Different number of source and dest resumes? Error out.
if (srcs && dst && srcs.length && dst.length && srcs.length !== dst.length) {
this.err(HMSTATUS.inputOutputParity, {
quit: true
});
}
// Validate the destination format (if specified)
targetVer = null;
if (opts.format) {
fmtUp = opts.format.trim().toUpperCase();
@ -75,13 +67,27 @@ Implementation of the 'convert' verb for HackMyResume.
});
}
}
// freshVerRegex = require '../utils/fresh-version-regex'
// matches = fmtUp.match freshVerRegex()
// # null
// # [ 'JRS@1.0', 'JRS', '1.0', index: 0, input: 'FRESH' ]
// # [ 'FRESH', 'FRESH', undefined, index: 0, input: 'FRESH' ]
// if not matches
// @err HMSTATUS.invalidSchemaVersion, data: opts.format.trim(), quit: true
// targetSchema = matches[1]
// targetVer = matches[2] || '1'
// If any errors have occurred this early, we're done.
if (this.hasError()) {
this.reject(this.errorCode);
return null;
}
// Map each source resume to the converted destination resume
results = _.map(srcs, function(src, idx) {
var r;
// Convert each resume in turn
r = _convertOne.call(this, src, dst, idx, fmtUp);
// Handle conversion errors
if (r.fluenterror) {
r.quit = opts.assert;
this.err(r.fluenterror, r);
@ -96,11 +102,9 @@ Implementation of the 'convert' verb for HackMyResume.
return results;
};
/** Private workhorse method. Convert a single resume. */
_convertOne = function(src, dst, idx, targetSchema) {
var err, rez, rinfo, srcFmt, targetFormat;
// Load the resume
rinfo = ResumeFactory.loadOne(src, {
format: null,
objectify: true,
@ -108,19 +112,23 @@ Implementation of the 'convert' verb for HackMyResume.
privatize: false
}
});
// If a load error occurs, report it and move on to the next file (if any)
if (rinfo.fluenterror) {
this.stat(HMEVENT.beforeConvert, {
srcFile: src,
srcFile: src, //rinfo.file
srcFmt: '???',
dstFile: dst[idx],
dstFmt: '???',
error: true
});
//@err rinfo.fluenterror, rinfo
return rinfo;
}
// Determine the resume's SOURCE format
// TODO: replace with detector component
rez = rinfo.rez;
srcFmt = '';
if (rez.meta && rez.meta.format) {
if (rez.meta && rez.meta.format) { //&& rez.meta.format.substr(0, 5).toUpperCase() == 'FRESH'
srcFmt = 'FRESH';
} else if (rez.basics) {
srcFmt = 'JRS';
@ -128,7 +136,9 @@ Implementation of the 'convert' verb for HackMyResume.
rinfo.fluenterror = HMSTATUS.unknownSchema;
return rinfo;
}
// Determine the TARGET format for the conversion
targetFormat = targetSchema || (srcFmt === 'JRS' ? 'FRESH' : 'JRS');
// Fire the beforeConvert event
this.stat(HMEVENT.beforeConvert, {
srcFile: rinfo.file,
srcFmt: srcFmt,
@ -136,9 +146,10 @@ Implementation of the 'convert' verb for HackMyResume.
dstFmt: targetFormat
});
try {
// Save it to the destination format
rez.saveAs(dst[idx], targetFormat);
} catch (_error) {
err = _error;
} catch (error) {
err = error;
if (err.badVer) {
return {
fluenterror: HMSTATUS.invalidSchemaVersion,

39
dist/verbs/create.js vendored
View File

@ -1,14 +1,12 @@
(function() {
/**
Implementation of the 'create' verb for HackMyResume.
@module verbs/create
@license MIT. See LICENSE.md for details.
*/
(function() {
var CreateVerb, HMEVENT, HMSTATUS, MKDIRP, PATH, Verb, _, _create, _createOne, chalk,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
/** Create a new empty resume in either FRESH or JRS format. */
/** Create a single new resume */
var CreateVerb, HMEVENT, HMSTATUS, MKDIRP, PATH, Verb, _, _create, _createOne, chalk;
MKDIRP = require('mkdirp');
@ -24,19 +22,12 @@ Implementation of the 'create' verb for HackMyResume.
HMEVENT = require('../core/event-codes');
module.exports = CreateVerb = (function(superClass) {
extend(CreateVerb, superClass);
function CreateVerb() {
CreateVerb.__super__.constructor.call(this, 'new', _create);
module.exports = CreateVerb = class CreateVerb extends Verb {
constructor() {
super('new', _create);
}
return CreateVerb;
})(Verb);
/** Create a new empty resume in either FRESH or JRS format. */
};
_create = function(src, dst, opts) {
var results;
@ -66,11 +57,8 @@ Implementation of the 'create' verb for HackMyResume.
return results;
};
/** Create a single new resume */
_createOne = function(t, opts) {
var RezClass, newRez, ret, safeFmt;
var RezClass, err, newRez, ret, safeFmt;
try {
ret = null;
safeFmt = opts.format.toUpperCase();
@ -78,15 +66,16 @@ Implementation of the 'create' verb for HackMyResume.
fmt: safeFmt,
file: t
});
MKDIRP.sync(PATH.dirname(t));
MKDIRP.sync(PATH.dirname(t)); // Ensure dest folder exists;
RezClass = require('../core/' + safeFmt.toLowerCase() + '-resume');
newRez = RezClass["default"]();
newRez = RezClass.default();
newRez.save(t);
ret = newRez;
} catch (_error) {
} catch (error) {
err = error;
ret = {
fluenterror: HMSTATUS.createError,
inner: _error
inner: err
};
} finally {
this.stat(HMEVENT.afterCreate, {

34
dist/verbs/peek.js vendored
View File

@ -1,14 +1,12 @@
(function() {
/**
Implementation of the 'peek' verb for HackMyResume.
@module verbs/peek
@license MIT. See LICENSE.md for details.
*/
(function() {
var HMEVENT, HMSTATUS, PeekVerb, Verb, _, __, _peek, _peekOne, safeLoadJSON,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
/** Peek at a resume, resume section, or resume field. */
/** Peek at a single resume, resume section, or resume field. */
var HMEVENT, HMSTATUS, PeekVerb, Verb, _, __, _peek, _peekOne, safeLoadJSON;
Verb = require('../verbs/verb');
@ -22,19 +20,12 @@ Implementation of the 'peek' verb for HackMyResume.
HMEVENT = require('../core/event-codes');
module.exports = PeekVerb = (function(superClass) {
extend(PeekVerb, superClass);
function PeekVerb() {
PeekVerb.__super__.constructor.call(this, 'peek', _peek);
module.exports = PeekVerb = class PeekVerb extends Verb {
constructor() {
super('peek', _peek);
}
return PeekVerb;
})(Verb);
/** Peek at a resume, resume section, or resume field. */
};
_peek = function(src, dst, opts) {
var objPath, results;
@ -54,6 +45,8 @@ Implementation of the 'peek' verb for HackMyResume.
if (tgt.error) {
this.setError(tgt.error.fluenterror, tgt.error);
}
//tgt.error.quit = opts.assert
//@err tgt.error.fluenterror, tgt.error
return tgt;
}, this);
if (this.hasError() && !opts.assert) {
@ -64,20 +57,20 @@ Implementation of the 'peek' verb for HackMyResume.
return results;
};
/** Peek at a single resume, resume section, or resume field. */
_peekOne = function(t, objPath) {
var errCode, obj, pkgError, tgt;
this.stat(HMEVENT.beforePeek, {
file: t,
target: objPath
});
// Load the input file JSON 1st
obj = safeLoadJSON(t);
// Fetch the requested object path (or the entire file)
tgt = null;
if (!obj.ex) {
tgt = objPath ? __.get(obj.json, objPath) : obj.json;
}
//# safeLoadJSON can only return a READ error or a PARSE error
pkgError = null;
if (obj.ex) {
errCode = obj.ex.op === 'parse' ? HMSTATUS.parseError : HMSTATUS.readError;
@ -89,6 +82,7 @@ Implementation of the 'peek' verb for HackMyResume.
inner: obj.ex
};
}
// Fire the 'afterPeek' event with collected info
this.stat(HMEVENT.afterPeek, {
file: t,
requested: objPath,

View File

@ -1,14 +1,21 @@
(function() {
/**
Implementation of the 'validate' verb for HackMyResume.
@module verbs/validate
@license MIT. See LICENSE.md for details.
*/
(function() {
var FS, HMEVENT, HMSTATUS, ResumeFactory, SyntaxErrorEx, ValidateVerb, Verb, _, _validate, _validateOne, chalk, safeLoadJSON,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
/**
Validate a single resume.
@returns {
file: <fileName>,
isValid: <validFlag>,
status: <validationStatus>,
violations: <validationErrors>,
schema: <schemaType>,
error: <errorObject>
}
*/
var FS, HMEVENT, HMSTATUS, ResumeFactory, SyntaxErrorEx, ValidateVerb, Verb, _, _validate, _validateOne, chalk, safeLoadJSON;
FS = require('fs');
@ -28,20 +35,15 @@ Implementation of the 'validate' verb for HackMyResume.
safeLoadJSON = require('../utils/safe-json-loader');
/** An invokable resume validation command. */
module.exports = ValidateVerb = (function(superClass) {
extend(ValidateVerb, superClass);
function ValidateVerb() {
ValidateVerb.__super__.constructor.call(this, 'validate', _validate);
module.exports = ValidateVerb = class ValidateVerb extends Verb {
constructor() {
super('validate', _validate);
}
return ValidateVerb;
})(Verb);
};
// Validate 1 to N resumes in FRESH or JSON Resume format.
_validate = function(sources, unused, opts) {
var results, schemas, validator;
if (!sources || !sources.length) {
@ -71,21 +73,8 @@ Implementation of the 'validate' verb for HackMyResume.
return results;
};
/**
Validate a single resume.
@returns {
file: <fileName>,
isValid: <validFlag>,
status: <validationStatus>,
violations: <validationErrors>,
schema: <schemaType>,
error: <errorObject>
}
*/
_validateOne = function(t, validator, schemas, opts) {
var errCode, obj, ret, validate;
var err, errCode, obj, ret, validate;
ret = {
file: t,
isValid: false,
@ -93,6 +82,7 @@ Implementation of the 'validate' verb for HackMyResume.
schema: '-----'
};
try {
// Read and parse the resume JSON. Won't throw.
obj = safeLoadJSON(t);
if (!obj.ex) {
if (obj.json.basics) {
@ -111,6 +101,7 @@ Implementation of the 'validate' verb for HackMyResume.
ret.violations = validate.errors;
}
} else {
// If failure, package JSON read/parse errors
if (obj.ex.op === 'parse') {
errCode = HMSTATUS.parseError;
ret.status = 'broken';
@ -124,10 +115,12 @@ Implementation of the 'validate' verb for HackMyResume.
quiet: errCode === HMSTATUS.readError
};
}
} catch (_error) {
} catch (error) {
err = error;
// Package any unexpected exceptions
ret.error = {
fluenterror: HMSTATUS.validateError,
inner: _error
inner: err
};
}
this.stat(HMEVENT.afterValidate, ret);

62
dist/verbs/verb.js vendored
View File

@ -1,11 +1,9 @@
(function() {
/**
Definition of the Verb class.
@module verbs/verb
@license MIT. See LICENSE.md for details.
*/
(function() {
var EVENTS, HMEVENT, Promise, Verb;
EVENTS = require('events');
@ -14,65 +12,57 @@ Definition of the Verb class.
Promise = require('pinkie-promise');
/**
An abstract invokable verb.
Provides base class functionality for verbs. Provide common services such as
error handling, event management, and promise support.
@class Verb
*/
module.exports = Verb = (function() {
module.exports = Verb = class Verb {
/** Constructor. Automatically called at creation. */
function Verb(moniker, workhorse) {
constructor(moniker, workhorse) {
this.moniker = moniker;
this.workhorse = workhorse;
this.emitter = new EVENTS.EventEmitter();
return;
}
/** Invoke the command. */
Verb.prototype.invoke = function() {
invoke() {
var argsArray, that;
// Sent the 'begin' notification for this verb
this.stat(HMEVENT.begin, {
cmd: this.moniker
});
// Prepare command arguments
argsArray = Array.prototype.slice.call(arguments);
// Create a promise for this verb instance
that = this;
return this.promise = new Promise(function(res, rej) {
that.resolve = res;
that.reject = rej;
that.workhorse.apply(that, argsArray);
});
};
}
/** Forward subscriptions to the event emitter. */
Verb.prototype.on = function() {
on() {
return this.emitter.on.apply(this.emitter, arguments);
};
}
/** Fire an arbitrary event, scoped to "hmr:". */
Verb.prototype.fire = function(evtName, payload) {
fire(evtName, payload) {
payload = payload || {};
payload.cmd = this.moniker;
this.emitter.emit('hmr:' + evtName, payload);
return true;
};
}
/** Handle an error condition. */
Verb.prototype.err = function(errorCode, payload, hot) {
err(errorCode, payload, hot) {
payload = payload || {};
payload.sub = payload.fluenterror = errorCode;
payload["throw"] = hot;
payload.throw = hot;
this.setError(errorCode, payload);
if (payload.quit) {
this.reject(errorCode);
@ -82,37 +72,29 @@ Definition of the Verb class.
throw payload;
}
return true;
};
}
/** Fire the 'hmr:status' error event. */
Verb.prototype.stat = function(subEvent, payload) {
stat(subEvent, payload) {
payload = payload || {};
payload.sub = subEvent;
this.fire('status', payload);
return true;
};
}
/** Has an error occurred during this verb invocation? */
Verb.prototype.hasError = function() {
hasError() {
return this.errorCode || this.errorObj;
};
}
/** Associate error info with the invocation. */
Verb.prototype.setError = function(code, obj) {
setError(code, obj) {
this.errorCode = code;
this.errorObj = obj;
}
};
return Verb;
})();
}).call(this);
//# sourceMappingURL=verb.js.map

View File

@ -49,33 +49,33 @@
"main": "dist/index.js",
"homepage": "https://github.com/hacksalot/HackMyResume",
"dependencies": {
"chalk": "^1.1.1",
"chalk": "^2.3.1",
"commander": "^2.9.0",
"copy": "^0.1.3",
"escape-latex": "^0.1.2",
"copy": "^0.3.1",
"escape-latex": "^1.0.0",
"extend": "^3.0.0",
"fresh-jrs-converter": "^1.0.0",
"fresh-resume-schema": "^1.0.0-beta",
"fresh-resume-starter": "^0.3.1",
"fresh-resume-validator": "^0.1.0",
"fresh-themes": "^0.16.0-beta",
"fs-extra": "^0.26.4",
"fresh-resume-validator": "^0.2.0",
"fresh-themes": "^0.17.0-beta",
"fs-extra": "^5.0.0",
"glob": "^7.1.2",
"handlebars": "^4.0.5",
"html": "0.0.10",
"html": "^1.0.0",
"is-my-json-valid": "^2.12.4",
"json-lint": "^0.1.0",
"jsonlint": "^1.6.2",
"lodash": "^3.10.1",
"lodash": "^4.17.5",
"marked": "^0.3.5",
"mkdirp": "^0.5.1",
"moment": "^2.11.1",
"parse-filepath": "^0.6.3",
"path-exists": "^2.1.0",
"parse-filepath": "^1.0.2",
"path-exists": "^3.0.0",
"pinkie-promise": "^2.0.0",
"printf": "^0.2.3",
"recursive-readdir-sync": "^1.0.6",
"simple-html-tokenizer": "^0.2.1",
"simple-html-tokenizer": "^0.4.3",
"slash": "^1.0.0",
"string-padding": "^1.0.2",
"string.prototype.endswith": "^0.2.0",
@ -84,23 +84,20 @@
"underscore": "^1.8.3",
"word-wrap": "^1.1.0",
"xml-escape": "^1.0.0",
"yamljs": "^0.2.4"
"yamljs": "^0.3.0"
},
"devDependencies": {
"chai": "*",
"chai-as-promised": "^7.1.1",
"dir-compare": "0.0.2",
"dir-compare": "^1.4.0",
"fresh-test-resumes": "^0.9.2",
"fresh-test-themes": "^0.2.0",
"fresh-theme-underscore": "^0.1.1",
"grunt": "*",
"grunt-cli": "^0.1.13",
"grunt-contrib-clean": "^0.7.0",
"grunt-contrib-coffee": "^0.13.0",
"grunt-contrib-copy": "^0.8.2",
"grunt-contrib-jshint": "^0.11.3",
"grunt-contrib-yuidoc": "^0.10.0",
"grunt-jsdoc": "^1.1.0",
"grunt-contrib-clean": "^1.1.0",
"grunt-contrib-coffee": "^2.0.0",
"grunt-contrib-copy": "^1.0.0",
"grunt-contrib-jshint": "^1.1.0",
"grunt-simple-mocha": "*",
"jsonresume-theme-boilerplate": "^0.1.2",
"jsonresume-theme-classy": "^1.0.9",

View File

@ -104,9 +104,9 @@ _parse = ( fileName, opts, eve ) ->
eve && eve.stat HME.afterParse, { file: fileName, data: ret.json, fmt: orgFormat }
return ret
catch
catch err
# Can be ENOENT, EACCES, SyntaxError, etc.
fluenterror: if rawData then HMS.parseError else HMS.readError
inner: _error
inner: err
raw: rawData
file: fileName

View File

@ -122,14 +122,14 @@ module.exports = class TemplateGenerator extends BaseGenerator
return
# Write the file
opts.beforeWrite? thisFilePath
opts.beforeWrite? data: thisFilePath
MKDIRP.sync PATH.dirname( thisFilePath )
if file.info.action != 'copy'
FS.writeFileSync thisFilePath, file.data, encoding: 'utf8', flags: 'w'
else
FS.copySync file.info.path, thisFilePath
opts.afterWrite? thisFilePath
opts.afterWrite? data: thisFilePath
# Post-processing
if @onAfterSave
@ -174,9 +174,9 @@ createSymLinks = ( curFmt, outFolder ) ->
try
FS.symlinkSync absTarg, absLoc, type
catch
catch err
succeeded = false
if _error.code == 'EEXIST'
if err.code == 'EEXIST'
FS.unlinkSync absLoc
try
FS.symlinkSync absTarg, absLoc, type

View File

@ -34,11 +34,11 @@ HandlebarsGenerator = module.exports =
assumeObjects: false
noEscape: data.opts.noescape
return template data
catch
catch err
throw
fluenterror:
HMSTATUS[ if template then 'invokeTemplate' else 'compileTemplate' ]
inner: _error
inner: err

View File

@ -24,12 +24,12 @@ UnderscoreGenerator = module.exports =
# Compile and run the Handlebars template.
t = _.template tpl
t data
catch
catch err
#console.dir _error
HMS = require '../core/status-codes'
throw
fluenterror: HMS[if t then 'invokeTemplate' else 'compileTemplate']
inner: _error
inner: err

View File

@ -12,15 +12,15 @@ module.exports = ( file ) ->
try
ret.raw = FS.readFileSync( file, 'utf8' );
ret.json = JSON.parse( ret.raw );
catch
catch err
# If we get here, either FS.readFileSync or JSON.parse failed.
# We'll return HMSTATUS.readError or HMSTATUS.parseError.
retRaw = ret.raw && ret.raw.trim()
ret.ex =
op: if retRaw then 'parse' else 'read'
inner:
if SyntaxErrorEx.is( _error )
then (new SyntaxErrorEx( _error, retRaw ))
else _error
if SyntaxErrorEx.is( err )
then (new SyntaxErrorEx( err, retRaw ))
else err
file: file
ret

View File

@ -24,6 +24,6 @@ module.exports = ( cmd, args, isSync, callback, param ) ->
callback?(info.error, param)
return cmd: cmd, inner: info.error
catch
callback?(_error, param)
_error
catch ex
callback?(ex, param)
ex

View File

@ -26,8 +26,8 @@ class SyntaxErrorEx
JSONLint = require 'jsonlint'
try
JSONLint.parse rawData
catch
@line = (/on line (\d+)/.exec _error)[1]
catch err
@line = (/on line (\d+)/.exec err)[1]
# Return true if the supplied parameter is a JavaScript SyntaxError

View File

@ -90,10 +90,10 @@ _build = ( src, dst, opts ) ->
return
theme = _opts.themeObj = _loadTheme tFolder
_addFreebieFormats theme
catch
catch err
newEx =
fluenterror: HMSTATUS.themeLoad
inner: _error
inner: err
attempted: _opts.theme
quit: true
@err HMSTATUS.themeLoad, newEx

View File

@ -58,10 +58,10 @@ _createOne = ( t, opts ) ->
newRez.save t
ret = newRez
return
catch
catch err
ret =
fluenterror: HMSTATUS.createError
inner: _error
inner: err
return
finally
@.stat HMEVENT.afterCreate, fmt: safeFmt, file: t, isError: ret.fluenterror

View File

@ -94,9 +94,9 @@ _validateOne = (t, validator, schemas, opts) ->
inner: obj.ex.inner,
quiet: errCode == HMSTATUS.readError
catch
catch err
# Package any unexpected exceptions
ret.error = fluenterror: HMSTATUS.validateError, inner: _error
ret.error = fluenterror: HMSTATUS.validateError, inner: err
@stat HMEVENT.afterValidate, ret
ret