Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@vencakrecl/pdf-generator

Package Overview
Dependencies
Maintainers
1
Versions
16
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@vencakrecl/pdf-generator - npm Package Compare versions

Comparing version 1.2.0 to 1.3.0-beta.0

1083

dist/pdf-generator.cjs.development.js

@@ -14,2 +14,38 @@ 'use strict';

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _extends() {

@@ -123,2 +159,756 @@ _extends = Object.assign || function (target) {

function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var runtime_1 = createCommonjsModule(function (module) {
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var runtime = (function (exports) {
var Op = Object.prototype;
var hasOwn = Op.hasOwnProperty;
var undefined$1; // More compressible than void 0.
var $Symbol = typeof Symbol === "function" ? Symbol : {};
var iteratorSymbol = $Symbol.iterator || "@@iterator";
var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
function define(obj, key, value) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
return obj[key];
}
try {
// IE 8 has a broken Object.defineProperty that only works on DOM objects.
define({}, "");
} catch (err) {
define = function(obj, key, value) {
return obj[key] = value;
};
}
function wrap(innerFn, outerFn, self, tryLocsList) {
// If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
var generator = Object.create(protoGenerator.prototype);
var context = new Context(tryLocsList || []);
// The ._invoke method unifies the implementations of the .next,
// .throw, and .return methods.
generator._invoke = makeInvokeMethod(innerFn, self, context);
return generator;
}
exports.wrap = wrap;
// Try/catch helper to minimize deoptimizations. Returns a completion
// record like context.tryEntries[i].completion. This interface could
// have been (and was previously) designed to take a closure to be
// invoked without arguments, but in all the cases we care about we
// already have an existing method we want to call, so there's no need
// to create a new function object. We can even get away with assuming
// the method takes exactly one argument, since that happens to be true
// in every case, so we don't have to touch the arguments object. The
// only additional allocation required is the completion record, which
// has a stable shape and so hopefully should be cheap to allocate.
function tryCatch(fn, obj, arg) {
try {
return { type: "normal", arg: fn.call(obj, arg) };
} catch (err) {
return { type: "throw", arg: err };
}
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed";
// Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement.
var ContinueSentinel = {};
// Dummy constructor functions that we use as the .constructor and
// .constructor.prototype properties for functions that return Generator
// objects. For full spec compliance, you may wish to configure your
// minifier not to mangle the names of these two functions.
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
// This is a polyfill for %IteratorPrototype% for environments that
// don't natively support it.
var IteratorPrototype = {};
IteratorPrototype[iteratorSymbol] = function () {
return this;
};
var getProto = Object.getPrototypeOf;
var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
if (NativeIteratorPrototype &&
NativeIteratorPrototype !== Op &&
hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
// This environment has a native %IteratorPrototype%; use it instead
// of the polyfill.
IteratorPrototype = NativeIteratorPrototype;
}
var Gp = GeneratorFunctionPrototype.prototype =
Generator.prototype = Object.create(IteratorPrototype);
GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
GeneratorFunctionPrototype.constructor = GeneratorFunction;
GeneratorFunction.displayName = define(
GeneratorFunctionPrototype,
toStringTagSymbol,
"GeneratorFunction"
);
// Helper for defining the .next, .throw, and .return methods of the
// Iterator interface in terms of a single ._invoke method.
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function(method) {
define(prototype, method, function(arg) {
return this._invoke(method, arg);
});
});
}
exports.isGeneratorFunction = function(genFun) {
var ctor = typeof genFun === "function" && genFun.constructor;
return ctor
? ctor === GeneratorFunction ||
// For the native GeneratorFunction constructor, the best we can
// do is to check its .name property.
(ctor.displayName || ctor.name) === "GeneratorFunction"
: false;
};
exports.mark = function(genFun) {
if (Object.setPrototypeOf) {
Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
} else {
genFun.__proto__ = GeneratorFunctionPrototype;
define(genFun, toStringTagSymbol, "GeneratorFunction");
}
genFun.prototype = Object.create(Gp);
return genFun;
};
// Within the body of any async function, `await x` is transformed to
// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
// `hasOwn.call(value, "__await")` to determine if the yielded value is
// meant to be awaited.
exports.awrap = function(arg) {
return { __await: arg };
};
function AsyncIterator(generator, PromiseImpl) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if (record.type === "throw") {
reject(record.arg);
} else {
var result = record.arg;
var value = result.value;
if (value &&
typeof value === "object" &&
hasOwn.call(value, "__await")) {
return PromiseImpl.resolve(value.__await).then(function(value) {
invoke("next", value, resolve, reject);
}, function(err) {
invoke("throw", err, resolve, reject);
});
}
return PromiseImpl.resolve(value).then(function(unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration.
result.value = unwrapped;
resolve(result);
}, function(error) {
// If a rejected Promise was yielded, throw the rejection back
// into the async generator function so it can be handled there.
return invoke("throw", error, resolve, reject);
});
}
}
var previousPromise;
function enqueue(method, arg) {
function callInvokeWithMethodAndArg() {
return new PromiseImpl(function(resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise =
// If enqueue has been called before, then we want to wait until
// all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially
// important to get this right, even though it requires care.
previousPromise ? previousPromise.then(
callInvokeWithMethodAndArg,
// Avoid propagating failures to Promises returned by later
// invocations of the iterator.
callInvokeWithMethodAndArg
) : callInvokeWithMethodAndArg();
}
// Define the unified helper method that is used to implement .next,
// .throw, and .return (see defineIteratorMethods).
this._invoke = enqueue;
}
defineIteratorMethods(AsyncIterator.prototype);
AsyncIterator.prototype[asyncIteratorSymbol] = function () {
return this;
};
exports.AsyncIterator = AsyncIterator;
// Note that simple async functions are implemented on top of
// AsyncIterator objects; they just return a Promise for the value of
// the final result produced by the iterator.
exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
if (PromiseImpl === void 0) PromiseImpl = Promise;
var iter = new AsyncIterator(
wrap(innerFn, outerFn, self, tryLocsList),
PromiseImpl
);
return exports.isGeneratorFunction(outerFn)
? iter // If outerFn is a generator, return the full iterator.
: iter.next().then(function(result) {
return result.done ? result.value : iter.next();
});
};
function makeInvokeMethod(innerFn, self, context) {
var state = GenStateSuspendedStart;
return function invoke(method, arg) {
if (state === GenStateExecuting) {
throw new Error("Generator is already running");
}
if (state === GenStateCompleted) {
if (method === "throw") {
throw arg;
}
// Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
return doneResult();
}
context.method = method;
context.arg = arg;
while (true) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if (context.method === "next") {
// Setting context._sent for legacy support of Babel's
// function.sent implementation.
context.sent = context._sent = context.arg;
} else if (context.method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw context.arg;
}
context.dispatchException(context.arg);
} else if (context.method === "return") {
context.abrupt("return", context.arg);
}
state = GenStateExecuting;
var record = tryCatch(innerFn, self, context);
if (record.type === "normal") {
// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done
? GenStateCompleted
: GenStateSuspendedYield;
if (record.arg === ContinueSentinel) {
continue;
}
return {
value: record.arg,
done: context.done
};
} else if (record.type === "throw") {
state = GenStateCompleted;
// Dispatch the exception by looping back around to the
// context.dispatchException(context.arg) call above.
context.method = "throw";
context.arg = record.arg;
}
}
};
}
// Call delegate.iterator[context.method](context.arg) and handle the
// result, either by returning a { value, done } result from the
// delegate iterator, or by modifying context.method and context.arg,
// setting context.delegate to null, and returning the ContinueSentinel.
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (method === undefined$1) {
// A .throw or .return when the delegate iterator has no .throw
// method always terminates the yield* loop.
context.delegate = null;
if (context.method === "throw") {
// Note: ["return"] must be used for ES3 parsing compatibility.
if (delegate.iterator["return"]) {
// If the delegate iterator has a return method, give it a
// chance to clean up.
context.method = "return";
context.arg = undefined$1;
maybeInvokeDelegate(delegate, context);
if (context.method === "throw") {
// If maybeInvokeDelegate(context) changed context.method from
// "return" to "throw", let that override the TypeError below.
return ContinueSentinel;
}
}
context.method = "throw";
context.arg = new TypeError(
"The iterator does not provide a 'throw' method");
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if (record.type === "throw") {
context.method = "throw";
context.arg = record.arg;
context.delegate = null;
return ContinueSentinel;
}
var info = record.arg;
if (! info) {
context.method = "throw";
context.arg = new TypeError("iterator result is not an object");
context.delegate = null;
return ContinueSentinel;
}
if (info.done) {
// Assign the result of the finished delegate to the temporary
// variable specified by delegate.resultName (see delegateYield).
context[delegate.resultName] = info.value;
// Resume execution at the desired location (see delegateYield).
context.next = delegate.nextLoc;
// If context.method was "throw" but the delegate handled the
// exception, let the outer generator proceed normally. If
// context.method was "next", forget context.arg since it has been
// "consumed" by the delegate iterator. If context.method was
// "return", allow the original .return call to continue in the
// outer generator.
if (context.method !== "return") {
context.method = "next";
context.arg = undefined$1;
}
} else {
// Re-yield the result returned by the delegate method.
return info;
}
// The delegate iterator is finished, so forget it and continue with
// the outer generator.
context.delegate = null;
return ContinueSentinel;
}
// Define Generator.prototype.{next,throw,return} in terms of the
// unified ._invoke helper method.
defineIteratorMethods(Gp);
define(Gp, toStringTagSymbol, "Generator");
// A Generator should always return itself as the iterator object when the
// @@iterator function is called on it. Some browsers' implementations of the
// iterator prototype chain incorrectly implement this, causing the Generator
// object to not be returned from this call. This ensures that doesn't happen.
// See https://github.com/facebook/regenerator/issues/274 for more details.
Gp[iteratorSymbol] = function() {
return this;
};
Gp.toString = function() {
return "[object Generator]";
};
function pushTryEntry(locs) {
var entry = { tryLoc: locs[0] };
if (1 in locs) {
entry.catchLoc = locs[1];
}
if (2 in locs) {
entry.finallyLoc = locs[2];
entry.afterLoc = locs[3];
}
this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal";
delete record.arg;
entry.completion = record;
}
function Context(tryLocsList) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [{ tryLoc: "root" }];
tryLocsList.forEach(pushTryEntry, this);
this.reset(true);
}
exports.keys = function(object) {
var keys = [];
for (var key in object) {
keys.push(key);
}
keys.reverse();
// Rather than returning an object with a next method, we keep
// things simple and return the next function itself.
return function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
}
// To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
};
};
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
}
if (typeof iterable.next === "function") {
return iterable;
}
if (!isNaN(iterable.length)) {
var i = -1, next = function next() {
while (++i < iterable.length) {
if (hasOwn.call(iterable, i)) {
next.value = iterable[i];
next.done = false;
return next;
}
}
next.value = undefined$1;
next.done = true;
return next;
};
return next.next = next;
}
}
// Return an iterator with no values.
return { next: doneResult };
}
exports.values = values;
function doneResult() {
return { value: undefined$1, done: true };
}
Context.prototype = {
constructor: Context,
reset: function(skipTempReset) {
this.prev = 0;
this.next = 0;
// Resetting context._sent for legacy support of Babel's
// function.sent implementation.
this.sent = this._sent = undefined$1;
this.done = false;
this.delegate = null;
this.method = "next";
this.arg = undefined$1;
this.tryEntries.forEach(resetTryEntry);
if (!skipTempReset) {
for (var name in this) {
// Not sure about the optimal order of these conditions:
if (name.charAt(0) === "t" &&
hasOwn.call(this, name) &&
!isNaN(+name.slice(1))) {
this[name] = undefined$1;
}
}
}
},
stop: function() {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") {
throw rootRecord.arg;
}
return this.rval;
},
dispatchException: function(exception) {
if (this.done) {
throw exception;
}
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
if (caught) {
// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
context.method = "next";
context.arg = undefined$1;
}
return !! caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") {
// Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
}
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
} else if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else if (hasCatch) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
}
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else {
throw new Error("try statement without catch or finally");
}
}
}
},
abrupt: function(type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev &&
hasOwn.call(entry, "finallyLoc") &&
this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
if (finallyEntry &&
(type === "break" ||
type === "continue") &&
finallyEntry.tryLoc <= arg &&
arg <= finallyEntry.finallyLoc) {
// Ignore the finally entry if control is not jumping to a
// location outside the try/catch block.
finallyEntry = null;
}
var record = finallyEntry ? finallyEntry.completion : {};
record.type = type;
record.arg = arg;
if (finallyEntry) {
this.method = "next";
this.next = finallyEntry.finallyLoc;
return ContinueSentinel;
}
return this.complete(record);
},
complete: function(record, afterLoc) {
if (record.type === "throw") {
throw record.arg;
}
if (record.type === "break" ||
record.type === "continue") {
this.next = record.arg;
} else if (record.type === "return") {
this.rval = this.arg = record.arg;
this.method = "return";
this.next = "end";
} else if (record.type === "normal" && afterLoc) {
this.next = afterLoc;
}
return ContinueSentinel;
},
finish: function(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) {
this.complete(entry.completion, entry.afterLoc);
resetTryEntry(entry);
return ContinueSentinel;
}
}
},
"catch": function(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
// The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw new Error("illegal catch attempt");
},
delegateYield: function(iterable, resultName, nextLoc) {
this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
};
if (this.method === "next") {
// Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
this.arg = undefined$1;
}
return ContinueSentinel;
}
};
// Regardless of whether this script is executing as a CommonJS module
// or not, return the runtime object so that we can declare the variable
// regeneratorRuntime in the outer scope, which allows this module to be
// injected easily by `bin/regenerator --include-runtime script.js`.
return exports;
}(
// If this script is executing as a CommonJS module, use module.exports
// as the regeneratorRuntime namespace. Otherwise create a new empty
// object. Either way, the resulting object will be used to initialize
// the regeneratorRuntime variable at the top of this file.
module.exports
));
try {
regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
// This module should not be running in strict mode, so the above
// assignment should always work unless something is misconfigured. Just
// in case runtime.js accidentally runs in strict mode, we can escape
// strict mode using a global Function call. This could conceivably fail
// if a Content Security Policy forbids using Function, but in that case
// the proper solution is to fix the accidental strict mode problem. If
// you've misconfigured your bundler to force strict mode and applied a
// CSP to forbid Function, and you're not willing to fix either of those
// problems, please detail your unique predicament in a GitHub issue.
Function("r", "regeneratorRuntime = r")(runtime);
}
});
var NullLogger = /*#__PURE__*/function () {

@@ -129,10 +919,14 @@ function NullLogger() {}

// @ts-ignore
_proto.log = function log(message) {// null function
};
} // @ts-ignore
;
_proto.info = function info(message) {// null function
};
} // @ts-ignore
;
_proto.warn = function warn(message) {// null function
};
} // @ts-ignore
;

@@ -146,19 +940,36 @@ _proto.error = function error(message) {// null function

var PdfRenderer = /*#__PURE__*/function () {
function PdfRenderer() {}
function PdfRenderer() {
this.browser = null;
this.logger = new NullLogger();
}
var _proto = PdfRenderer.prototype;
_proto.start = function start() {
try {
var _this2 = this;
_proto.start = /*#__PURE__*/function () {
var _start = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee() {
return runtime_1.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return puppeteer.launch();
return Promise.resolve(puppeteer.launch()).then(function (_puppeteer$launch) {
_this2.browser = _puppeteer$launch;
_this2.logger = new NullLogger();
});
} catch (e) {
return Promise.reject(e);
case 2:
this.browser = _context.sent;
case 3:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function start() {
return _start.apply(this, arguments);
}
};
return start;
}();
_proto.setLogger = function setLogger(logger) {

@@ -168,77 +979,124 @@ this.logger = logger;

_proto.render = function render(content) {
try {
var _temp3 = function _temp3() {
return Promise.resolve(_this4.browser.newPage()).then(function (page) {
page.on('console', function (msg) {
var message = "PAGE LOG:: " + msg.text();
_proto.render = /*#__PURE__*/function () {
var _render = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee2(content) {
var _this$browser,
_this = this;
switch (msg.type()) {
case 'error':
{
_this4.logger.error(message);
var page, data;
return runtime_1.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!(!this.browser || !this.browser.isConnected())) {
_context2.next = 3;
break;
}
break;
}
_context2.next = 3;
return this.start();
case 'info':
{
_this4.logger.info(message);
case 3:
if (this.browser) {
_context2.next = 5;
break;
}
break;
}
throw new Error('Browser does not start.');
case 'warning':
{
_this4.logger.warn(message);
case 5:
_context2.next = 7;
return (_this$browser = this.browser) == null ? void 0 : _this$browser.newPage();
break;
}
case 7:
page = _context2.sent;
page.on('console', function (msg) {
var message = "PAGE LOG:: " + msg.text();
default:
{
_this4.logger.log(message);
switch (msg.type()) {
case 'error':
{
_this.logger.error(message);
break;
}
case 'info':
{
_this.logger.info(message);
break;
}
case 'warning':
{
_this.logger.warn(message);
break;
}
default:
{
_this.logger.log(message);
}
}
}
});
return Promise.resolve(page.setContent(content)).then(function () {
return Promise.resolve(page.pdf()).then(function (data) {
return Promise.resolve(page.close()).then(function () {
return data;
});
});
});
});
};
_context2.next = 11;
return page.setContent(content);
var _this4 = this;
case 11:
_context2.next = 13;
return page.pdf();
var _temp4 = function () {
if (!_this4.browser || !_this4.browser.isConnected()) {
return Promise.resolve(_this4.start()).then(function () {});
case 13:
data = _context2.sent;
_context2.next = 16;
return page.close();
case 16:
return _context2.abrupt("return", data);
case 17:
case "end":
return _context2.stop();
}
}
}();
}, _callee2, this);
}));
return Promise.resolve(_temp4 && _temp4.then ? _temp4.then(_temp3) : _temp3(_temp4));
} catch (e) {
return Promise.reject(e);
function render(_x) {
return _render.apply(this, arguments);
}
};
_proto.stop = function stop() {
try {
var _this6 = this;
return render;
}();
var _temp6 = function () {
if (_this6.browser) {
return Promise.resolve(_this6.browser.close()).then(function () {});
_proto.stop = /*#__PURE__*/function () {
var _stop = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee3() {
return runtime_1.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
if (!this.browser) {
_context3.next = 3;
break;
}
_context3.next = 3;
return this.browser.close();
case 3:
case "end":
return _context3.stop();
}
}
}();
}, _callee3, this);
}));
return Promise.resolve(_temp6 && _temp6.then ? _temp6.then(function () {}) : void 0);
} catch (e) {
return Promise.reject(e);
function stop() {
return _stop.apply(this, arguments);
}
};
return stop;
}();
return PdfRenderer;

@@ -419,2 +1277,3 @@ }();

this.templateLoader = new TemplateLoader(this.templatesPath);
this.server = null;
}

@@ -430,39 +1289,73 @@

_proto.start = function start() {
try {
var _this2 = this;
_proto.start = /*#__PURE__*/function () {
var _start = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee() {
var _this = this;
var app = express();
app.use('/static', express["static"](_this2.templatesPath));
_this2.server = app.listen(_this2.httpPort, function () {
_this2.logger.info("Starting HTTP server for static files on " + _this2.httpPort);
});
return Promise.resolve(_this2.pdfRenderer.start()).then(function () {});
} catch (e) {
return Promise.reject(e);
var app;
return runtime_1.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
app = express();
app.use('/static', express["static"](this.templatesPath));
this.server = app.listen(this.httpPort, function () {
_this.logger.info("Starting HTTP server for static files on " + _this.httpPort);
});
_context.next = 5;
return this.pdfRenderer.start();
case 5:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function start() {
return _start.apply(this, arguments);
}
};
_proto.stop = function stop() {
try {
var _this4 = this;
return start;
}();
return Promise.resolve(_this4.pdfRenderer.stop()).then(function () {
if (_this4.server) {
_this4.server.close(function () {
_this4.logger.info('Closing HTTP server for static files');
});
_proto.stop = /*#__PURE__*/function () {
var _stop = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee2() {
var _this2 = this;
return runtime_1.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return this.pdfRenderer.stop();
case 2:
if (this.server) {
this.server.close(function () {
_this2.logger.info('Closing HTTP server for static files');
});
}
case 3:
case "end":
return _context2.stop();
}
}
});
} catch (e) {
return Promise.reject(e);
}, _callee2, this);
}));
function stop() {
return _stop.apply(this, arguments);
}
};
return stop;
}();
_proto.loadTemplates = function loadTemplates() {
var _this5 = this;
var _this3 = this;
var templates = this.templateLoader.load();
templates.forEach(function (item) {
_this5.htmlRenderer.addTemplate(item);
_this3.htmlRenderer.addTemplate(item);
});

@@ -469,0 +1362,0 @@ };

2

dist/pdf-generator.cjs.production.min.js

@@ -1,2 +0,2 @@

"use strict";function t(t){return t&&"object"==typeof t&&"default"in t?t.default:t}Object.defineProperty(exports,"__esModule",{value:!0});var e=t(require("express")),r=t(require("puppeteer")),n=t(require("pug")),o=t(require("ajv")),i=t(require("path")),s=t(require("fs"));function a(){return(a=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t}).apply(this,arguments)}function u(t){return(u=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function c(t,e){return(c=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function f(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return!1}}function h(t,e,r){return(h=f()?Reflect.construct:function(t,e,r){var n=[null];n.push.apply(n,e);var o=new(Function.bind.apply(t,n));return r&&c(o,r.prototype),o}).apply(null,arguments)}function l(t){var e="function"==typeof Map?new Map:void 0;return(l=function(t){if(null===t||-1===Function.toString.call(t).indexOf("[native code]"))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,r)}function r(){return h(t,arguments,u(this).constructor)}return r.prototype=Object.create(t.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),c(r,t)})(t)}var p=function(){function t(){}var e=t.prototype;return e.log=function(t){},e.info=function(t){},e.warn=function(t){},e.error=function(t){},t}(),d=function(){function t(){}var e=t.prototype;return e.start=function(){try{var t=this;return Promise.resolve(r.launch()).then((function(e){t.browser=e,t.logger=new p}))}catch(t){return Promise.reject(t)}},e.setLogger=function(t){this.logger=t},e.render=function(t){try{var e=function(){return Promise.resolve(r.browser.newPage()).then((function(e){return e.on("console",(function(t){var e="PAGE LOG:: "+t.text();switch(t.type()){case"error":r.logger.error(e);break;case"info":r.logger.info(e);break;case"warning":r.logger.warn(e);break;default:r.logger.log(e)}})),Promise.resolve(e.setContent(t)).then((function(){return Promise.resolve(e.pdf()).then((function(t){return Promise.resolve(e.close()).then((function(){return t}))}))}))}))},r=this,n=function(){if(!r.browser||!r.browser.isConnected())return Promise.resolve(r.start()).then((function(){}))}();return Promise.resolve(n&&n.then?n.then(e):e())}catch(t){return Promise.reject(t)}},e.stop=function(){try{var t=this,e=function(){if(t.browser)return Promise.resolve(t.browser.close()).then((function(){}))}();return Promise.resolve(e&&e.then?e.then((function(){})):void 0)}catch(t){return Promise.reject(t)}},t}(),g=function(t){var e,r;function n(e,r){var n;return(n=t.call(this,e)||this).errors=r,n}return r=t,(e=n).prototype=Object.create(r.prototype),e.prototype.constructor=e,e.__proto__=r,n}(l(Error)),m=function(){function t(){this.templates={}}var e=t.prototype;return e.addTemplate=function(t){if(this.templates[t.getId()])throw new Error('Template with key "'+t.getId()+'" already exists.');this.templates[t.getId()]=t},e.getTemplate=function(t){if(!this.templates[t])throw new Error('Template with key "'+t+'" does not exists.');return this.templates[t]},e.getIds=function(){return Object.keys(this.templates)},e.render=function(t,e){void 0===e&&(e={});var r=this.getTemplate(t),o=r.validate(e);if(o.length)throw new g('Template with key "'+t+'" is not valid.',o);return n.renderFile(r.getPath(),a({cache:!0},e))},t}(),v=function(){function t(t,e,r){void 0===r&&(r={}),this.schema={},this.id=t,this.path=e,this.schema=r;var n=new o;this.ajvValidate=n.compile(this.schema)}var e=t.prototype;return e.getId=function(){return this.id},e.getPath=function(){return this.path},e.getSchema=function(){return this.schema},e.validate=function(t){return void 0===t&&(t={}),this.ajvValidate(t)?[]:this.ajvValidate.errors},t}(),y=function(){function t(t){this.templateName="template.pug",this.schemaName="schema.json",this.dirPath=t,this.logger=new p}var e=t.prototype;return e.setLogger=function(t){this.logger=t},e.load=function(){var t=this,e=s.readdirSync(this.dirPath,"utf8"),r=[];return e.forEach((function(e){var n=i.join(t.dirPath,e,t.templateName),o=i.join(t.dirPath,e,t.schemaName);if(s.existsSync(n)){var a={};s.existsSync(o)?a=JSON.parse(s.readFileSync(o).toString()):t.logger.info('Schema "'+o+'" does not exists (not required).'),r.push(new v(e,n,a))}else t.logger.warn('Template "'+n+'" does not exists.')})),r},t}();exports.PdfGenerator=function(){function t(t,e){void 0===t&&(t=__dirname),void 0===e&&(e=3e3),this.templatesPath=t,this.httpPort=e,this.htmlRenderer=new m,this.pdfRenderer=new d,this.logger=new p,this.templateLoader=new y(this.templatesPath)}var r=t.prototype;return r.setLogger=function(t){this.logger=t,this.templateLoader.setLogger(t),this.pdfRenderer.setLogger(t)},r.start=function(){try{var t=this,r=e();return r.use("/static",e.static(t.templatesPath)),t.server=r.listen(t.httpPort,(function(){t.logger.info("Starting HTTP server for static files on "+t.httpPort)})),Promise.resolve(t.pdfRenderer.start()).then((function(){}))}catch(t){return Promise.reject(t)}},r.stop=function(){try{var t=this;return Promise.resolve(t.pdfRenderer.stop()).then((function(){t.server&&t.server.close((function(){t.logger.info("Closing HTTP server for static files")}))}))}catch(t){return Promise.reject(t)}},r.loadTemplates=function(){var t=this;this.templateLoader.load().forEach((function(e){t.htmlRenderer.addTemplate(e)}))},r.addTemplate=function(t,e,r){void 0===e&&(e="template"),void 0===r&&(r={}),this.htmlRenderer.addTemplate(new v(t,i.join(this.templatesPath,e),r))},r.getTemplateIds=function(){return this.htmlRenderer.getIds()},r.generate=function(t,e){return this.pdfRenderer.render(this.htmlRenderer.render(t,a({baseUrl:"http://localhost:"+this.httpPort+"/static"},e)))},t}();
"use strict";function t(t){return t&&"object"==typeof t&&"default"in t?t.default:t}Object.defineProperty(exports,"__esModule",{value:!0});var e=t(require("express")),r=t(require("puppeteer")),n=t(require("pug")),o=t(require("ajv")),i=t(require("path")),a=t(require("fs"));function c(t,e,r,n,o,i,a){try{var c=t[i](a),s=c.value}catch(t){return void r(t)}c.done?e(s):Promise.resolve(s).then(n,o)}function s(t){return function(){var e=this,r=arguments;return new Promise((function(n,o){var i=t.apply(e,r);function a(t){c(i,n,o,a,s,"next",t)}function s(t){c(i,n,o,a,s,"throw",t)}a(void 0)}))}}function u(){return(u=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t}).apply(this,arguments)}function h(t){return(h=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function f(t,e){return(f=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function l(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return!1}}function p(t,e,r){return(p=l()?Reflect.construct:function(t,e,r){var n=[null];n.push.apply(n,e);var o=new(Function.bind.apply(t,n));return r&&f(o,r.prototype),o}).apply(null,arguments)}function d(t){var e="function"==typeof Map?new Map:void 0;return(d=function(t){if(null===t||-1===Function.toString.call(t).indexOf("[native code]"))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,r)}function r(){return p(t,arguments,h(this).constructor)}return r.prototype=Object.create(t.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),f(r,t)})(t)}var v,y=(function(t){var e=function(t){var e=Object.prototype,r=e.hasOwnProperty,n="function"==typeof Symbol?Symbol:{},o=n.iterator||"@@iterator",i=n.asyncIterator||"@@asyncIterator",a=n.toStringTag||"@@toStringTag";function c(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{c({},"")}catch(t){c=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var o=Object.create((e&&e.prototype instanceof f?e:f).prototype),i=new P(n||[]);return o._invoke=function(t,e,r){var n="suspendedStart";return function(o,i){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===o)throw i;return{value:void 0,done:!0}}for(r.method=o,r.arg=i;;){var a=r.delegate;if(a){var c=x(a,r);if(c){if(c===h)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var s=u(t,e,r);if("normal"===s.type){if(n=r.done?"completed":"suspendedYield",s.arg===h)continue;return{value:s.arg,done:r.done}}"throw"===s.type&&(n="completed",r.method="throw",r.arg=s.arg)}}}(t,r,i),o}function u(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=s;var h={};function f(){}function l(){}function p(){}var d={};d[o]=function(){return this};var v=Object.getPrototypeOf,y=v&&v(v(_([])));y&&y!==e&&r.call(y,o)&&(d=y);var g=p.prototype=f.prototype=Object.create(d);function m(t){["next","throw","return"].forEach((function(e){c(t,e,(function(t){return this._invoke(e,t)}))}))}function w(t,e){var n;this._invoke=function(o,i){function a(){return new e((function(n,a){!function n(o,i,a,c){var s=u(t[o],t,i);if("throw"!==s.type){var h=s.arg,f=h.value;return f&&"object"==typeof f&&r.call(f,"__await")?e.resolve(f.__await).then((function(t){n("next",t,a,c)}),(function(t){n("throw",t,a,c)})):e.resolve(f).then((function(t){h.value=t,a(h)}),(function(t){return n("throw",t,a,c)}))}c(s.arg)}(o,i,n,a)}))}return n=n?n.then(a,a):a()}}function x(t,e){var r=t.iterator[e.method];if(void 0===r){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=void 0,x(t,e),"throw"===e.method))return h;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return h}var n=u(r,t.iterator,e.arg);if("throw"===n.type)return e.method="throw",e.arg=n.arg,e.delegate=null,h;var o=n.arg;return o?o.done?(e[t.resultName]=o.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=void 0),e.delegate=null,h):o:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,h)}function b(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function L(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function P(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(b,this),this.reset(!0)}function _(t){if(t){var e=t[o];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var n=-1,i=function e(){for(;++n<t.length;)if(r.call(t,n))return e.value=t[n],e.done=!1,e;return e.value=void 0,e.done=!0,e};return i.next=i}}return{next:j}}function j(){return{value:void 0,done:!0}}return l.prototype=g.constructor=p,p.constructor=l,l.displayName=c(p,a,"GeneratorFunction"),t.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===l||"GeneratorFunction"===(e.displayName||e.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,p):(t.__proto__=p,c(t,a,"GeneratorFunction")),t.prototype=Object.create(g),t},t.awrap=function(t){return{__await:t}},m(w.prototype),w.prototype[i]=function(){return this},t.AsyncIterator=w,t.async=function(e,r,n,o,i){void 0===i&&(i=Promise);var a=new w(s(e,r,n,o),i);return t.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},m(g),c(g,a,"Generator"),g[o]=function(){return this},g.toString=function(){return"[object Generator]"},t.keys=function(t){var e=[];for(var r in t)e.push(r);return e.reverse(),function r(){for(;e.length;){var n=e.pop();if(n in t)return r.value=n,r.done=!1,r}return r.done=!0,r}},t.values=_,P.prototype={constructor:P,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(L),!t)for(var e in this)"t"===e.charAt(0)&&r.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=void 0)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function n(r,n){return a.type="throw",a.arg=t,e.next=r,n&&(e.method="next",e.arg=void 0),!!n}for(var o=this.tryEntries.length-1;o>=0;--o){var i=this.tryEntries[o],a=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var c=r.call(i,"catchLoc"),s=r.call(i,"finallyLoc");if(c&&s){if(this.prev<i.catchLoc)return n(i.catchLoc,!0);if(this.prev<i.finallyLoc)return n(i.finallyLoc)}else if(c){if(this.prev<i.catchLoc)return n(i.catchLoc,!0)}else{if(!s)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return n(i.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,h):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),h},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),L(r),h}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;L(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,r){return this.delegate={iterator:_(t),resultName:e,nextLoc:r},"next"===this.method&&(this.arg=void 0),h}},t}(t.exports);try{regeneratorRuntime=e}catch(t){Function("r","regeneratorRuntime = r")(e)}}(v={exports:{}}),v.exports),g=function(){function t(){}var e=t.prototype;return e.log=function(t){},e.info=function(t){},e.warn=function(t){},e.error=function(t){},t}(),m=function(){function t(){this.browser=null,this.logger=new g}var e=t.prototype;return e.start=function(){var t=s(y.mark((function t(){return y.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,r.launch();case 2:this.browser=t.sent;case 3:case"end":return t.stop()}}),t,this)})));return function(){return t.apply(this,arguments)}}(),e.setLogger=function(t){this.logger=t},e.render=function(){var t=s(y.mark((function t(e){var r,n,o,i=this;return y.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this.browser&&this.browser.isConnected()){t.next=3;break}return t.next=3,this.start();case 3:if(this.browser){t.next=5;break}throw new Error("Browser does not start.");case 5:return t.next=7,null==(r=this.browser)?void 0:r.newPage();case 7:return(n=t.sent).on("console",(function(t){var e="PAGE LOG:: "+t.text();switch(t.type()){case"error":i.logger.error(e);break;case"info":i.logger.info(e);break;case"warning":i.logger.warn(e);break;default:i.logger.log(e)}})),t.next=11,n.setContent(e);case 11:return t.next=13,n.pdf();case 13:return o=t.sent,t.next=16,n.close();case 16:return t.abrupt("return",o);case 17:case"end":return t.stop()}}),t,this)})));return function(e){return t.apply(this,arguments)}}(),e.stop=function(){var t=s(y.mark((function t(){return y.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!this.browser){t.next=3;break}return t.next=3,this.browser.close();case 3:case"end":return t.stop()}}),t,this)})));return function(){return t.apply(this,arguments)}}(),t}(),w=function(t){var e,r;function n(e,r){var n;return(n=t.call(this,e)||this).errors=r,n}return r=t,(e=n).prototype=Object.create(r.prototype),e.prototype.constructor=e,e.__proto__=r,n}(d(Error)),x=function(){function t(){this.templates={}}var e=t.prototype;return e.addTemplate=function(t){if(this.templates[t.getId()])throw new Error('Template with key "'+t.getId()+'" already exists.');this.templates[t.getId()]=t},e.getTemplate=function(t){if(!this.templates[t])throw new Error('Template with key "'+t+'" does not exists.');return this.templates[t]},e.getIds=function(){return Object.keys(this.templates)},e.render=function(t,e){void 0===e&&(e={});var r=this.getTemplate(t),o=r.validate(e);if(o.length)throw new w('Template with key "'+t+'" is not valid.',o);return n.renderFile(r.getPath(),u({cache:!0},e))},t}(),b=function(){function t(t,e,r){void 0===r&&(r={}),this.schema={},this.id=t,this.path=e,this.schema=r;var n=new o;this.ajvValidate=n.compile(this.schema)}var e=t.prototype;return e.getId=function(){return this.id},e.getPath=function(){return this.path},e.getSchema=function(){return this.schema},e.validate=function(t){return void 0===t&&(t={}),this.ajvValidate(t)?[]:this.ajvValidate.errors},t}(),L=function(){function t(t){this.templateName="template.pug",this.schemaName="schema.json",this.dirPath=t,this.logger=new g}var e=t.prototype;return e.setLogger=function(t){this.logger=t},e.load=function(){var t=this,e=a.readdirSync(this.dirPath,"utf8"),r=[];return e.forEach((function(e){var n=i.join(t.dirPath,e,t.templateName),o=i.join(t.dirPath,e,t.schemaName);if(a.existsSync(n)){var c={};a.existsSync(o)?c=JSON.parse(a.readFileSync(o).toString()):t.logger.info('Schema "'+o+'" does not exists (not required).'),r.push(new b(e,n,c))}else t.logger.warn('Template "'+n+'" does not exists.')})),r},t}();exports.PdfGenerator=function(){function t(t,e){void 0===t&&(t=__dirname),void 0===e&&(e=3e3),this.templatesPath=t,this.httpPort=e,this.htmlRenderer=new x,this.pdfRenderer=new m,this.logger=new g,this.templateLoader=new L(this.templatesPath),this.server=null}var r=t.prototype;return r.setLogger=function(t){this.logger=t,this.templateLoader.setLogger(t),this.pdfRenderer.setLogger(t)},r.start=function(){var t=s(y.mark((function t(){var r,n=this;return y.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return(r=e()).use("/static",e.static(this.templatesPath)),this.server=r.listen(this.httpPort,(function(){n.logger.info("Starting HTTP server for static files on "+n.httpPort)})),t.next=5,this.pdfRenderer.start();case 5:case"end":return t.stop()}}),t,this)})));return function(){return t.apply(this,arguments)}}(),r.stop=function(){var t=s(y.mark((function t(){var e=this;return y.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.pdfRenderer.stop();case 2:this.server&&this.server.close((function(){e.logger.info("Closing HTTP server for static files")}));case 3:case"end":return t.stop()}}),t,this)})));return function(){return t.apply(this,arguments)}}(),r.loadTemplates=function(){var t=this;this.templateLoader.load().forEach((function(e){t.htmlRenderer.addTemplate(e)}))},r.addTemplate=function(t,e,r){void 0===e&&(e="template"),void 0===r&&(r={}),this.htmlRenderer.addTemplate(new b(t,i.join(this.templatesPath,e),r))},r.getTemplateIds=function(){return this.htmlRenderer.getIds()},r.generate=function(t,e){return this.pdfRenderer.render(this.htmlRenderer.render(t,u({baseUrl:"http://localhost:"+this.httpPort+"/static"},e)))},t}();
//# sourceMappingURL=pdf-generator.cjs.production.min.js.map

@@ -8,2 +8,38 @@ import express from 'express';

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _extends() {

@@ -117,2 +153,756 @@ _extends = Object.assign || function (target) {

function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var runtime_1 = createCommonjsModule(function (module) {
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var runtime = (function (exports) {
var Op = Object.prototype;
var hasOwn = Op.hasOwnProperty;
var undefined$1; // More compressible than void 0.
var $Symbol = typeof Symbol === "function" ? Symbol : {};
var iteratorSymbol = $Symbol.iterator || "@@iterator";
var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
function define(obj, key, value) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
return obj[key];
}
try {
// IE 8 has a broken Object.defineProperty that only works on DOM objects.
define({}, "");
} catch (err) {
define = function(obj, key, value) {
return obj[key] = value;
};
}
function wrap(innerFn, outerFn, self, tryLocsList) {
// If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
var generator = Object.create(protoGenerator.prototype);
var context = new Context(tryLocsList || []);
// The ._invoke method unifies the implementations of the .next,
// .throw, and .return methods.
generator._invoke = makeInvokeMethod(innerFn, self, context);
return generator;
}
exports.wrap = wrap;
// Try/catch helper to minimize deoptimizations. Returns a completion
// record like context.tryEntries[i].completion. This interface could
// have been (and was previously) designed to take a closure to be
// invoked without arguments, but in all the cases we care about we
// already have an existing method we want to call, so there's no need
// to create a new function object. We can even get away with assuming
// the method takes exactly one argument, since that happens to be true
// in every case, so we don't have to touch the arguments object. The
// only additional allocation required is the completion record, which
// has a stable shape and so hopefully should be cheap to allocate.
function tryCatch(fn, obj, arg) {
try {
return { type: "normal", arg: fn.call(obj, arg) };
} catch (err) {
return { type: "throw", arg: err };
}
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed";
// Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement.
var ContinueSentinel = {};
// Dummy constructor functions that we use as the .constructor and
// .constructor.prototype properties for functions that return Generator
// objects. For full spec compliance, you may wish to configure your
// minifier not to mangle the names of these two functions.
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
// This is a polyfill for %IteratorPrototype% for environments that
// don't natively support it.
var IteratorPrototype = {};
IteratorPrototype[iteratorSymbol] = function () {
return this;
};
var getProto = Object.getPrototypeOf;
var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
if (NativeIteratorPrototype &&
NativeIteratorPrototype !== Op &&
hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
// This environment has a native %IteratorPrototype%; use it instead
// of the polyfill.
IteratorPrototype = NativeIteratorPrototype;
}
var Gp = GeneratorFunctionPrototype.prototype =
Generator.prototype = Object.create(IteratorPrototype);
GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
GeneratorFunctionPrototype.constructor = GeneratorFunction;
GeneratorFunction.displayName = define(
GeneratorFunctionPrototype,
toStringTagSymbol,
"GeneratorFunction"
);
// Helper for defining the .next, .throw, and .return methods of the
// Iterator interface in terms of a single ._invoke method.
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function(method) {
define(prototype, method, function(arg) {
return this._invoke(method, arg);
});
});
}
exports.isGeneratorFunction = function(genFun) {
var ctor = typeof genFun === "function" && genFun.constructor;
return ctor
? ctor === GeneratorFunction ||
// For the native GeneratorFunction constructor, the best we can
// do is to check its .name property.
(ctor.displayName || ctor.name) === "GeneratorFunction"
: false;
};
exports.mark = function(genFun) {
if (Object.setPrototypeOf) {
Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
} else {
genFun.__proto__ = GeneratorFunctionPrototype;
define(genFun, toStringTagSymbol, "GeneratorFunction");
}
genFun.prototype = Object.create(Gp);
return genFun;
};
// Within the body of any async function, `await x` is transformed to
// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
// `hasOwn.call(value, "__await")` to determine if the yielded value is
// meant to be awaited.
exports.awrap = function(arg) {
return { __await: arg };
};
function AsyncIterator(generator, PromiseImpl) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if (record.type === "throw") {
reject(record.arg);
} else {
var result = record.arg;
var value = result.value;
if (value &&
typeof value === "object" &&
hasOwn.call(value, "__await")) {
return PromiseImpl.resolve(value.__await).then(function(value) {
invoke("next", value, resolve, reject);
}, function(err) {
invoke("throw", err, resolve, reject);
});
}
return PromiseImpl.resolve(value).then(function(unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration.
result.value = unwrapped;
resolve(result);
}, function(error) {
// If a rejected Promise was yielded, throw the rejection back
// into the async generator function so it can be handled there.
return invoke("throw", error, resolve, reject);
});
}
}
var previousPromise;
function enqueue(method, arg) {
function callInvokeWithMethodAndArg() {
return new PromiseImpl(function(resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise =
// If enqueue has been called before, then we want to wait until
// all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially
// important to get this right, even though it requires care.
previousPromise ? previousPromise.then(
callInvokeWithMethodAndArg,
// Avoid propagating failures to Promises returned by later
// invocations of the iterator.
callInvokeWithMethodAndArg
) : callInvokeWithMethodAndArg();
}
// Define the unified helper method that is used to implement .next,
// .throw, and .return (see defineIteratorMethods).
this._invoke = enqueue;
}
defineIteratorMethods(AsyncIterator.prototype);
AsyncIterator.prototype[asyncIteratorSymbol] = function () {
return this;
};
exports.AsyncIterator = AsyncIterator;
// Note that simple async functions are implemented on top of
// AsyncIterator objects; they just return a Promise for the value of
// the final result produced by the iterator.
exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
if (PromiseImpl === void 0) PromiseImpl = Promise;
var iter = new AsyncIterator(
wrap(innerFn, outerFn, self, tryLocsList),
PromiseImpl
);
return exports.isGeneratorFunction(outerFn)
? iter // If outerFn is a generator, return the full iterator.
: iter.next().then(function(result) {
return result.done ? result.value : iter.next();
});
};
function makeInvokeMethod(innerFn, self, context) {
var state = GenStateSuspendedStart;
return function invoke(method, arg) {
if (state === GenStateExecuting) {
throw new Error("Generator is already running");
}
if (state === GenStateCompleted) {
if (method === "throw") {
throw arg;
}
// Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
return doneResult();
}
context.method = method;
context.arg = arg;
while (true) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if (context.method === "next") {
// Setting context._sent for legacy support of Babel's
// function.sent implementation.
context.sent = context._sent = context.arg;
} else if (context.method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw context.arg;
}
context.dispatchException(context.arg);
} else if (context.method === "return") {
context.abrupt("return", context.arg);
}
state = GenStateExecuting;
var record = tryCatch(innerFn, self, context);
if (record.type === "normal") {
// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done
? GenStateCompleted
: GenStateSuspendedYield;
if (record.arg === ContinueSentinel) {
continue;
}
return {
value: record.arg,
done: context.done
};
} else if (record.type === "throw") {
state = GenStateCompleted;
// Dispatch the exception by looping back around to the
// context.dispatchException(context.arg) call above.
context.method = "throw";
context.arg = record.arg;
}
}
};
}
// Call delegate.iterator[context.method](context.arg) and handle the
// result, either by returning a { value, done } result from the
// delegate iterator, or by modifying context.method and context.arg,
// setting context.delegate to null, and returning the ContinueSentinel.
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (method === undefined$1) {
// A .throw or .return when the delegate iterator has no .throw
// method always terminates the yield* loop.
context.delegate = null;
if (context.method === "throw") {
// Note: ["return"] must be used for ES3 parsing compatibility.
if (delegate.iterator["return"]) {
// If the delegate iterator has a return method, give it a
// chance to clean up.
context.method = "return";
context.arg = undefined$1;
maybeInvokeDelegate(delegate, context);
if (context.method === "throw") {
// If maybeInvokeDelegate(context) changed context.method from
// "return" to "throw", let that override the TypeError below.
return ContinueSentinel;
}
}
context.method = "throw";
context.arg = new TypeError(
"The iterator does not provide a 'throw' method");
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if (record.type === "throw") {
context.method = "throw";
context.arg = record.arg;
context.delegate = null;
return ContinueSentinel;
}
var info = record.arg;
if (! info) {
context.method = "throw";
context.arg = new TypeError("iterator result is not an object");
context.delegate = null;
return ContinueSentinel;
}
if (info.done) {
// Assign the result of the finished delegate to the temporary
// variable specified by delegate.resultName (see delegateYield).
context[delegate.resultName] = info.value;
// Resume execution at the desired location (see delegateYield).
context.next = delegate.nextLoc;
// If context.method was "throw" but the delegate handled the
// exception, let the outer generator proceed normally. If
// context.method was "next", forget context.arg since it has been
// "consumed" by the delegate iterator. If context.method was
// "return", allow the original .return call to continue in the
// outer generator.
if (context.method !== "return") {
context.method = "next";
context.arg = undefined$1;
}
} else {
// Re-yield the result returned by the delegate method.
return info;
}
// The delegate iterator is finished, so forget it and continue with
// the outer generator.
context.delegate = null;
return ContinueSentinel;
}
// Define Generator.prototype.{next,throw,return} in terms of the
// unified ._invoke helper method.
defineIteratorMethods(Gp);
define(Gp, toStringTagSymbol, "Generator");
// A Generator should always return itself as the iterator object when the
// @@iterator function is called on it. Some browsers' implementations of the
// iterator prototype chain incorrectly implement this, causing the Generator
// object to not be returned from this call. This ensures that doesn't happen.
// See https://github.com/facebook/regenerator/issues/274 for more details.
Gp[iteratorSymbol] = function() {
return this;
};
Gp.toString = function() {
return "[object Generator]";
};
function pushTryEntry(locs) {
var entry = { tryLoc: locs[0] };
if (1 in locs) {
entry.catchLoc = locs[1];
}
if (2 in locs) {
entry.finallyLoc = locs[2];
entry.afterLoc = locs[3];
}
this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal";
delete record.arg;
entry.completion = record;
}
function Context(tryLocsList) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [{ tryLoc: "root" }];
tryLocsList.forEach(pushTryEntry, this);
this.reset(true);
}
exports.keys = function(object) {
var keys = [];
for (var key in object) {
keys.push(key);
}
keys.reverse();
// Rather than returning an object with a next method, we keep
// things simple and return the next function itself.
return function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
}
// To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
};
};
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
}
if (typeof iterable.next === "function") {
return iterable;
}
if (!isNaN(iterable.length)) {
var i = -1, next = function next() {
while (++i < iterable.length) {
if (hasOwn.call(iterable, i)) {
next.value = iterable[i];
next.done = false;
return next;
}
}
next.value = undefined$1;
next.done = true;
return next;
};
return next.next = next;
}
}
// Return an iterator with no values.
return { next: doneResult };
}
exports.values = values;
function doneResult() {
return { value: undefined$1, done: true };
}
Context.prototype = {
constructor: Context,
reset: function(skipTempReset) {
this.prev = 0;
this.next = 0;
// Resetting context._sent for legacy support of Babel's
// function.sent implementation.
this.sent = this._sent = undefined$1;
this.done = false;
this.delegate = null;
this.method = "next";
this.arg = undefined$1;
this.tryEntries.forEach(resetTryEntry);
if (!skipTempReset) {
for (var name in this) {
// Not sure about the optimal order of these conditions:
if (name.charAt(0) === "t" &&
hasOwn.call(this, name) &&
!isNaN(+name.slice(1))) {
this[name] = undefined$1;
}
}
}
},
stop: function() {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") {
throw rootRecord.arg;
}
return this.rval;
},
dispatchException: function(exception) {
if (this.done) {
throw exception;
}
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
if (caught) {
// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
context.method = "next";
context.arg = undefined$1;
}
return !! caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") {
// Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
}
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
} else if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else if (hasCatch) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
}
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else {
throw new Error("try statement without catch or finally");
}
}
}
},
abrupt: function(type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev &&
hasOwn.call(entry, "finallyLoc") &&
this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
if (finallyEntry &&
(type === "break" ||
type === "continue") &&
finallyEntry.tryLoc <= arg &&
arg <= finallyEntry.finallyLoc) {
// Ignore the finally entry if control is not jumping to a
// location outside the try/catch block.
finallyEntry = null;
}
var record = finallyEntry ? finallyEntry.completion : {};
record.type = type;
record.arg = arg;
if (finallyEntry) {
this.method = "next";
this.next = finallyEntry.finallyLoc;
return ContinueSentinel;
}
return this.complete(record);
},
complete: function(record, afterLoc) {
if (record.type === "throw") {
throw record.arg;
}
if (record.type === "break" ||
record.type === "continue") {
this.next = record.arg;
} else if (record.type === "return") {
this.rval = this.arg = record.arg;
this.method = "return";
this.next = "end";
} else if (record.type === "normal" && afterLoc) {
this.next = afterLoc;
}
return ContinueSentinel;
},
finish: function(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) {
this.complete(entry.completion, entry.afterLoc);
resetTryEntry(entry);
return ContinueSentinel;
}
}
},
"catch": function(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
// The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw new Error("illegal catch attempt");
},
delegateYield: function(iterable, resultName, nextLoc) {
this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
};
if (this.method === "next") {
// Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
this.arg = undefined$1;
}
return ContinueSentinel;
}
};
// Regardless of whether this script is executing as a CommonJS module
// or not, return the runtime object so that we can declare the variable
// regeneratorRuntime in the outer scope, which allows this module to be
// injected easily by `bin/regenerator --include-runtime script.js`.
return exports;
}(
// If this script is executing as a CommonJS module, use module.exports
// as the regeneratorRuntime namespace. Otherwise create a new empty
// object. Either way, the resulting object will be used to initialize
// the regeneratorRuntime variable at the top of this file.
module.exports
));
try {
regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
// This module should not be running in strict mode, so the above
// assignment should always work unless something is misconfigured. Just
// in case runtime.js accidentally runs in strict mode, we can escape
// strict mode using a global Function call. This could conceivably fail
// if a Content Security Policy forbids using Function, but in that case
// the proper solution is to fix the accidental strict mode problem. If
// you've misconfigured your bundler to force strict mode and applied a
// CSP to forbid Function, and you're not willing to fix either of those
// problems, please detail your unique predicament in a GitHub issue.
Function("r", "regeneratorRuntime = r")(runtime);
}
});
var NullLogger = /*#__PURE__*/function () {

@@ -123,10 +913,14 @@ function NullLogger() {}

// @ts-ignore
_proto.log = function log(message) {// null function
};
} // @ts-ignore
;
_proto.info = function info(message) {// null function
};
} // @ts-ignore
;
_proto.warn = function warn(message) {// null function
};
} // @ts-ignore
;

@@ -140,19 +934,36 @@ _proto.error = function error(message) {// null function

var PdfRenderer = /*#__PURE__*/function () {
function PdfRenderer() {}
function PdfRenderer() {
this.browser = null;
this.logger = new NullLogger();
}
var _proto = PdfRenderer.prototype;
_proto.start = function start() {
try {
var _this2 = this;
_proto.start = /*#__PURE__*/function () {
var _start = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee() {
return runtime_1.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return puppeteer.launch();
return Promise.resolve(puppeteer.launch()).then(function (_puppeteer$launch) {
_this2.browser = _puppeteer$launch;
_this2.logger = new NullLogger();
});
} catch (e) {
return Promise.reject(e);
case 2:
this.browser = _context.sent;
case 3:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function start() {
return _start.apply(this, arguments);
}
};
return start;
}();
_proto.setLogger = function setLogger(logger) {

@@ -162,77 +973,124 @@ this.logger = logger;

_proto.render = function render(content) {
try {
var _temp3 = function _temp3() {
return Promise.resolve(_this4.browser.newPage()).then(function (page) {
page.on('console', function (msg) {
var message = "PAGE LOG:: " + msg.text();
_proto.render = /*#__PURE__*/function () {
var _render = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee2(content) {
var _this$browser,
_this = this;
switch (msg.type()) {
case 'error':
{
_this4.logger.error(message);
var page, data;
return runtime_1.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!(!this.browser || !this.browser.isConnected())) {
_context2.next = 3;
break;
}
break;
}
_context2.next = 3;
return this.start();
case 'info':
{
_this4.logger.info(message);
case 3:
if (this.browser) {
_context2.next = 5;
break;
}
break;
}
throw new Error('Browser does not start.');
case 'warning':
{
_this4.logger.warn(message);
case 5:
_context2.next = 7;
return (_this$browser = this.browser) == null ? void 0 : _this$browser.newPage();
break;
}
case 7:
page = _context2.sent;
page.on('console', function (msg) {
var message = "PAGE LOG:: " + msg.text();
default:
{
_this4.logger.log(message);
switch (msg.type()) {
case 'error':
{
_this.logger.error(message);
break;
}
case 'info':
{
_this.logger.info(message);
break;
}
case 'warning':
{
_this.logger.warn(message);
break;
}
default:
{
_this.logger.log(message);
}
}
}
});
return Promise.resolve(page.setContent(content)).then(function () {
return Promise.resolve(page.pdf()).then(function (data) {
return Promise.resolve(page.close()).then(function () {
return data;
});
});
});
});
};
_context2.next = 11;
return page.setContent(content);
var _this4 = this;
case 11:
_context2.next = 13;
return page.pdf();
var _temp4 = function () {
if (!_this4.browser || !_this4.browser.isConnected()) {
return Promise.resolve(_this4.start()).then(function () {});
case 13:
data = _context2.sent;
_context2.next = 16;
return page.close();
case 16:
return _context2.abrupt("return", data);
case 17:
case "end":
return _context2.stop();
}
}
}();
}, _callee2, this);
}));
return Promise.resolve(_temp4 && _temp4.then ? _temp4.then(_temp3) : _temp3(_temp4));
} catch (e) {
return Promise.reject(e);
function render(_x) {
return _render.apply(this, arguments);
}
};
_proto.stop = function stop() {
try {
var _this6 = this;
return render;
}();
var _temp6 = function () {
if (_this6.browser) {
return Promise.resolve(_this6.browser.close()).then(function () {});
_proto.stop = /*#__PURE__*/function () {
var _stop = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee3() {
return runtime_1.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
if (!this.browser) {
_context3.next = 3;
break;
}
_context3.next = 3;
return this.browser.close();
case 3:
case "end":
return _context3.stop();
}
}
}();
}, _callee3, this);
}));
return Promise.resolve(_temp6 && _temp6.then ? _temp6.then(function () {}) : void 0);
} catch (e) {
return Promise.reject(e);
function stop() {
return _stop.apply(this, arguments);
}
};
return stop;
}();
return PdfRenderer;

@@ -413,2 +1271,3 @@ }();

this.templateLoader = new TemplateLoader(this.templatesPath);
this.server = null;
}

@@ -424,39 +1283,73 @@

_proto.start = function start() {
try {
var _this2 = this;
_proto.start = /*#__PURE__*/function () {
var _start = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee() {
var _this = this;
var app = express();
app.use('/static', express["static"](_this2.templatesPath));
_this2.server = app.listen(_this2.httpPort, function () {
_this2.logger.info("Starting HTTP server for static files on " + _this2.httpPort);
});
return Promise.resolve(_this2.pdfRenderer.start()).then(function () {});
} catch (e) {
return Promise.reject(e);
var app;
return runtime_1.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
app = express();
app.use('/static', express["static"](this.templatesPath));
this.server = app.listen(this.httpPort, function () {
_this.logger.info("Starting HTTP server for static files on " + _this.httpPort);
});
_context.next = 5;
return this.pdfRenderer.start();
case 5:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function start() {
return _start.apply(this, arguments);
}
};
_proto.stop = function stop() {
try {
var _this4 = this;
return start;
}();
return Promise.resolve(_this4.pdfRenderer.stop()).then(function () {
if (_this4.server) {
_this4.server.close(function () {
_this4.logger.info('Closing HTTP server for static files');
});
_proto.stop = /*#__PURE__*/function () {
var _stop = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee2() {
var _this2 = this;
return runtime_1.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return this.pdfRenderer.stop();
case 2:
if (this.server) {
this.server.close(function () {
_this2.logger.info('Closing HTTP server for static files');
});
}
case 3:
case "end":
return _context2.stop();
}
}
});
} catch (e) {
return Promise.reject(e);
}, _callee2, this);
}));
function stop() {
return _stop.apply(this, arguments);
}
};
return stop;
}();
_proto.loadTemplates = function loadTemplates() {
var _this5 = this;
var _this3 = this;
var templates = this.templateLoader.load();
templates.forEach(function (item) {
_this5.htmlRenderer.addTemplate(item);
_this3.htmlRenderer.addTemplate(item);
});

@@ -463,0 +1356,0 @@ };

@@ -6,2 +6,3 @@ /// <reference types="node" />

private logger;
constructor();
start(): Promise<void>;

@@ -8,0 +9,0 @@ setLogger(logger: Logger): void;

{
"name": "@vencakrecl/pdf-generator",
"author": "Venca Krecl <venca.email@gmail.com>",
"version": "1.2.0",
"version": "1.3.0-beta.0",
"description": "Package for convert HTML to PDF by headless Chrome.",

@@ -20,29 +20,27 @@ "license": "MIT",

"scripts": {
"test": "jest .",
"start": "tsdx watch",
"build": "tsdx build",
"test": "tsdx test",
"lint": "tsdx lint",
"lint-fix": "tsdx lint src test --fix",
"build": "tsdx build",
"watch": "tsdx watch",
"prepare": "tsdx build",
"publish-package": "npm run-script build && npm publish --access public"
},
"devDependencies": {
"@types/express": "^4.17.7",
"@types/jest": "^26.0.10",
"@size-limit/preset-small-lib": "^4.9.1",
"@types/express": "^4.17.11",
"@types/jest": "^26.0.20",
"@types/pug": "^2.0.4",
"@types/puppeteer": "^3.0.1",
"@typescript-eslint/eslint-plugin": "^3.9.0",
"bootstrap": "^4.5.2",
"eslint": "^7.7.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-prettier": "^3.1.4",
"jest": "26.4.0",
"minimist": "^1.2.5",
"prettier": "^2.0.5",
"tsdx": "^0.13.2"
"@types/puppeteer": "^5.4.2",
"bootstrap": "^4.6.0",
"husky": "^4.3.8",
"tsdx": "^0.14.1",
"tslib": "^2.1.0",
"typescript": "^4.1.3"
},
"dependencies": {
"ajv": "^6.12.3",
"ajv": "^7.0.3",
"express": "^4.17.1",
"pug": "^3.0.0",
"puppeteer": "^5.2.1"
"puppeteer": "^5.5.0"
},

@@ -52,2 +50,3 @@ "main": "dist/index.js",

"types": "dist/index.d.ts",
"module": "dist/mylib.esm.js",
"files": [

@@ -59,3 +58,9 @@ "dist",

"README.md"
]
],
"prettier": {
"printWidth": 120,
"semi": false,
"singleQuote": true,
"trailingComma": "es5"
}
}

@@ -38,3 +38,3 @@ import Ajv, { ErrorObject, ValidateFunction } from 'ajv'

if (!isValid) {
return this.ajvValidate.errors
return this.ajvValidate.errors as Array<ErrorObject>
}

@@ -41,0 +41,0 @@

@@ -26,3 +26,3 @@ import fs from 'fs'

const templates: Template[] = []
dirs.forEach((key) => {
dirs.forEach(key => {
const templatePath = path.join(this.dirPath, key, this.templateName)

@@ -29,0 +29,0 @@ const schemaPath = path.join(this.dirPath, key, this.schemaName)

import Logger from './Logger'
class NullLogger implements Logger {
// @ts-ignore
log(message?: string, ...args: unknown[]): void {
// null function
}
// @ts-ignore
info(message?: string, ...args: unknown[]): void {
// null function
}
// @ts-ignore
warn(message?: string, ...args: unknown[]): void {
// null function
}
// @ts-ignore
error(message?: string, ...args: unknown[]): void {

@@ -14,0 +18,0 @@ // null function

@@ -7,8 +7,12 @@ import puppeteer from 'puppeteer'

class PdfRenderer {
private browser: Browser
private browser: Browser | null
private logger: Logger
constructor() {
this.browser = null
this.logger = new NullLogger()
}
public async start(): Promise<void> {
this.browser = await puppeteer.launch()
this.logger = new NullLogger()
}

@@ -25,4 +29,9 @@

const page = await this.browser.newPage()
page.on('console', (msg) => {
if (!this.browser) {
throw new Error('Browser does not start.')
}
const page = await this.browser?.newPage()
page.on('console', msg => {
const message = `PAGE LOG:: ${msg.text()}`

@@ -29,0 +38,0 @@ switch (msg.type()) {

@@ -12,3 +12,3 @@ import express from 'express'

class PdfGenerator {
private server: http.Server
private server: http.Server | null
private readonly httpPort: number

@@ -28,2 +28,3 @@ private readonly templatesPath: string

this.templateLoader = new TemplateLoader(this.templatesPath)
this.server = null
}

@@ -61,3 +62,3 @@

templates.forEach((item) => {
templates.forEach(item => {
this.htmlRenderer.addTemplate(item)

@@ -64,0 +65,0 @@ })

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc