UNPKG

docxtemplater

Version:

Generate docx, pptx, and xlsx from templates (Word, Powerpoint and Excel documents), from Node.js, the Browser and the command line

1,350 lines (1,327 loc) 188 kB
/******/ (function() { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 673: /***/ (function(module) { module.exports = { XMLSerializer: window.XMLSerializer, DOMParser: window.DOMParser, XMLDocument: window.XMLDocument }; /***/ }), /***/ 891: /***/ (function(module) { var ctXML = "[Content_Types].xml"; function collectContentTypes(overrides, defaults, zip) { var partNames = {}; for (var _i2 = 0; _i2 < overrides.length; _i2++) { var override = overrides[_i2]; var contentType = override.getAttribute("ContentType"); var partName = override.getAttribute("PartName").substr(1); partNames[partName] = contentType; } var _loop = function _loop() { var def = defaults[_i4]; var contentType = def.getAttribute("ContentType"); var extension = def.getAttribute("Extension"); zip.file(/./).map(function (_ref) { var name = _ref.name; if (name.slice(name.length - extension.length) === extension && !partNames[name] && name !== ctXML) { partNames[name] = contentType; } }); }; for (var _i4 = 0; _i4 < defaults.length; _i4++) { _loop(); } return partNames; } module.exports = collectContentTypes; /***/ }), /***/ 356: /***/ (function(module) { var coreContentType = "application/vnd.openxmlformats-package.core-properties+xml"; var appContentType = "application/vnd.openxmlformats-officedocument.extended-properties+xml"; var customContentType = "application/vnd.openxmlformats-officedocument.custom-properties+xml"; var settingsContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml"; var diagramDataContentType = "application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml"; var diagramDrawingContentType = "application/vnd.ms-office.drawingml.diagramDrawing+xml"; module.exports = { settingsContentType: settingsContentType, coreContentType: coreContentType, appContentType: appContentType, customContentType: customContentType, diagramDataContentType: diagramDataContentType, diagramDrawingContentType: diagramDrawingContentType }; /***/ }), /***/ 207: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } var _require = __webpack_require__(673), DOMParser = _require.DOMParser, XMLSerializer = _require.XMLSerializer; var _require2 = __webpack_require__(946), throwXmlTagNotFound = _require2.throwXmlTagNotFound; var _require3 = __webpack_require__(320), last = _require3.last, first = _require3.first; function isWhiteSpace(value) { return /^[ \n\r\t]+$/.test(value); } function parser(tag) { return { get: function get(scope) { if (tag === ".") { return scope; } if (scope) { return scope[tag]; } return scope; } }; } var attrToRegex = {}; function setSingleAttribute(partValue, attr, attrValue) { var regex; // Stryker disable next-line all : because this is an optimisation if (attrToRegex[attr]) { regex = attrToRegex[attr]; } else { regex = new RegExp("(<.* ".concat(attr, "=\")([^\"]*)(\".*)$")); attrToRegex[attr] = regex; } if (regex.test(partValue)) { return partValue.replace(regex, "$1".concat(attrValue, "$3")); } var end = partValue.lastIndexOf("/>"); if (end === -1) { end = partValue.lastIndexOf(">"); } return partValue.substr(0, end) + " ".concat(attr, "=\"").concat(attrValue, "\"") + partValue.substr(end); } function getSingleAttribute(value, attributeName) { var index = value.indexOf(" ".concat(attributeName, "=\"")); if (index === -1) { return null; } var startIndex = value.substr(index).search(/["']/) + index; var endIndex = value.substr(startIndex + 1).search(/["']/) + startIndex; return value.substr(startIndex + 1, endIndex - startIndex); } function endsWith(str, suffix) { return str.indexOf(suffix, str.length - suffix.length) !== -1; } function startsWith(str, prefix) { return str.substring(0, prefix.length) === prefix; } function getDuplicates(arr) { var duplicates = []; var hash = {}, result = []; for (var i = 0, l = arr.length; i < l; ++i) { if (!hash[arr[i]]) { hash[arr[i]] = true; result.push(arr[i]); } else { duplicates.push(arr[i]); } } return duplicates; } function uniq(arr) { var hash = {}, result = []; for (var i = 0, l = arr.length; i < l; ++i) { if (!hash[arr[i]]) { hash[arr[i]] = true; result.push(arr[i]); } } return result; } function chunkBy(parsed, f) { var chunks = [[]]; for (var _i2 = 0; _i2 < parsed.length; _i2++) { var p = parsed[_i2]; var currentChunk = chunks[chunks.length - 1]; var res = f(p); if (res === "start") { chunks.push([p]); } else if (res === "end") { currentChunk.push(p); chunks.push([]); } else { currentChunk.push(p); } } // Remove empty chunks var result = []; for (var _i4 = 0; _i4 < chunks.length; _i4++) { var chunk = chunks[_i4]; if (chunk.length > 0) { result.push(chunk); } } return result; } function getDefaults() { return { errorLogging: "json", stripInvalidXMLChars: false, paragraphLoop: false, nullGetter: function nullGetter(part) { return part.module ? "" : "undefined"; }, xmlFileNames: ["[Content_Types].xml"], parser: parser, linebreaks: false, fileTypeConfig: null, delimiters: { start: "{", end: "}" }, syntax: { changeDelimiterPrefix: "=" } }; } function xml2str(xmlNode) { return new XMLSerializer().serializeToString(xmlNode).replace(/xmlns(:[a-z0-9]+)?="" ?/g, ""); } function str2xml(str) { if (str.charCodeAt(0) === 65279) { // BOM sequence str = str.substr(1); } return new DOMParser().parseFromString(str, "text/xml"); } var charMap = [["&", "&amp;"], ["<", "&lt;"], [">", "&gt;"], ['"', "&quot;"], ["'", "&apos;"]]; var charMapRegexes = charMap.map(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), endChar = _ref2[0], startChar = _ref2[1]; return { rstart: new RegExp(startChar, "g"), rend: new RegExp(endChar, "g"), start: startChar, end: endChar }; }); function wordToUtf8(string) { for (var i = charMapRegexes.length - 1; i >= 0; i--) { var r = charMapRegexes[i]; string = string.replace(r.rstart, r.end); } return string; } function utf8ToWord(string) { // To make sure that the object given is a string (this is a noop for strings). string = string.toString(); var r; for (var i = 0, l = charMapRegexes.length; i < l; i++) { r = charMapRegexes[i]; string = string.replace(r.rend, r.start); } return string; } // This function is written with for loops for performance function concatArrays(arrays) { var result = []; for (var _i6 = 0; _i6 < arrays.length; _i6++) { var array = arrays[_i6]; for (var _i8 = 0; _i8 < array.length; _i8++) { var el = array[_i8]; result.push(el); } } return result; } function pushArray(array1, array2) { if (!array2) { return array1; } for (var i = 0, len = array2.length; i < len; i++) { array1.push(array2[i]); } return array1; } var spaceRegexp = new RegExp(String.fromCharCode(160), "g"); function convertSpaces(s) { return s.replace(spaceRegexp, " "); } function pregMatchAll(regex, content) { /* regex is a string, content is the content. It returns an array of all matches with their offset, for example: regex=la content=lolalolilala returns: [ {array: {0: 'la'}, offset: 2}, {array: {0: 'la'}, offset: 8}, {array: {0: 'la'}, offset: 10} ] */ var matchArray = []; var match; while ((match = regex.exec(content)) != null) { matchArray.push({ array: match, offset: match.index }); } return matchArray; } function isEnding(value, element) { return value === "</" + element + ">"; } function isStarting(value, element) { return value.indexOf("<" + element) === 0 && [">", " ", "/"].indexOf(value[element.length + 1]) !== -1; } function getRight(parsed, element, index) { var val = getRightOrNull(parsed, element, index); if (val !== null) { return val; } throwXmlTagNotFound({ position: "right", element: element, parsed: parsed, index: index }); } function getRightOrNull(parsed, elements, index) { if (typeof elements === "string") { elements = [elements]; } var level = 1; for (var i = index, l = parsed.length; i < l; i++) { var part = parsed[i]; for (var _i10 = 0, _elements2 = elements; _i10 < _elements2.length; _i10++) { var element = _elements2[_i10]; if (isEnding(part.value, element)) { level--; } if (isStarting(part.value, element)) { level++; } if (level === 0) { return i; } } } return null; } function getLeft(parsed, element, index) { var val = getLeftOrNull(parsed, element, index); if (val !== null) { return val; } throwXmlTagNotFound({ position: "left", element: element, parsed: parsed, index: index }); } function getLeftOrNull(parsed, elements, index) { if (typeof elements === "string") { elements = [elements]; } var level = 1; for (var i = index; i >= 0; i--) { var part = parsed[i]; for (var _i12 = 0, _elements4 = elements; _i12 < _elements4.length; _i12++) { var element = _elements4[_i12]; if (isStarting(part.value, element)) { level--; } if (isEnding(part.value, element)) { level++; } if (level === 0) { return i; } } } return null; } // Stryker disable all : because those are functions that depend on the parsed // structure based and we don't want minimal code here, but rather code that // makes things clear. function isTagStart(tagType, _ref3) { var type = _ref3.type, tag = _ref3.tag, position = _ref3.position; return type === "tag" && tag === tagType && (position === "start" || position === "selfclosing"); } function isTagEnd(tagType, _ref4) { var type = _ref4.type, tag = _ref4.tag, position = _ref4.position; return type === "tag" && tag === tagType && position === "end"; } function isParagraphStart(_ref5) { var type = _ref5.type, tag = _ref5.tag, position = _ref5.position; return ["w:p", "a:p"].indexOf(tag) !== -1 && type === "tag" && position === "start"; } function isParagraphEnd(_ref6) { var type = _ref6.type, tag = _ref6.tag, position = _ref6.position; return ["w:p", "a:p"].indexOf(tag) !== -1 && type === "tag" && position === "end"; } function isTextStart(_ref7) { var type = _ref7.type, position = _ref7.position, text = _ref7.text; return text && type === "tag" && position === "start"; } function isTextEnd(_ref8) { var type = _ref8.type, position = _ref8.position, text = _ref8.text; return text && type === "tag" && position === "end"; } function isContent(_ref9) { var type = _ref9.type, position = _ref9.position; return type === "placeholder" || type === "content" && position === "insidetag"; } function isModule(_ref10, modules) { var module = _ref10.module, type = _ref10.type; if (!(modules instanceof Array)) { modules = [modules]; } return type === "placeholder" && modules.indexOf(module) !== -1; } // Stryker restore all var corruptCharacters = /[\x00-\x08\x0B\x0C\x0E-\x1F]/; // 00 NUL '\0' (null character) // 01 SOH (start of heading) // 02 STX (start of text) // 03 ETX (end of text) // 04 EOT (end of transmission) // 05 ENQ (enquiry) // 06 ACK (acknowledge) // 07 BEL '\a' (bell) // 08 BS '\b' (backspace) // 0B VT '\v' (vertical tab) // 0C FF '\f' (form feed) // 0E SO (shift out) // 0F SI (shift in) // 10 DLE (data link escape) // 11 DC1 (device control 1) // 12 DC2 (device control 2) // 13 DC3 (device control 3) // 14 DC4 (device control 4) // 15 NAK (negative ack.) // 16 SYN (synchronous idle) // 17 ETB (end of trans. blk) // 18 CAN (cancel) // 19 EM (end of medium) // 1A SUB (substitute) // 1B ESC (escape) // 1C FS (file separator) // 1D GS (group separator) // 1E RS (record separator) // 1F US (unit separator) function hasCorruptCharacters(string) { return corruptCharacters.test(string); } function removeCorruptCharacters(string) { return string.replace(corruptCharacters, ""); } function invertMap(map) { var invertedMap = {}; for (var key in map) { var value = map[key]; invertedMap[value] || (invertedMap[value] = []); invertedMap[value].push(key); } return invertedMap; } // This ensures that the sort is stable. The default Array.sort of the browser // is not stable in firefox, as the JS spec does not enforce the sort to be // stable. function stableSort(arr, compare) { // Stryker disable all : in previous versions of Chrome, sort was not stable by itself, so we had to add this. This is to support older versions of JS runners. return arr.map(function (item, index) { return { item: item, index: index }; }).sort(function (a, b) { return compare(a.item, b.item) || a.index - b.index; }).map(function (_ref11) { var item = _ref11.item; return item; }); // Stryker restore all } module.exports = { endsWith: endsWith, startsWith: startsWith, isContent: isContent, isParagraphStart: isParagraphStart, isParagraphEnd: isParagraphEnd, isTagStart: isTagStart, isTagEnd: isTagEnd, isTextStart: isTextStart, isTextEnd: isTextEnd, isStarting: isStarting, isEnding: isEnding, isModule: isModule, uniq: uniq, getDuplicates: getDuplicates, chunkBy: chunkBy, last: last, first: first, xml2str: xml2str, str2xml: str2xml, getRightOrNull: getRightOrNull, getRight: getRight, getLeftOrNull: getLeftOrNull, getLeft: getLeft, pregMatchAll: pregMatchAll, convertSpaces: convertSpaces, charMapRegexes: charMapRegexes, hasCorruptCharacters: hasCorruptCharacters, removeCorruptCharacters: removeCorruptCharacters, getDefaults: getDefaults, wordToUtf8: wordToUtf8, utf8ToWord: utf8ToWord, concatArrays: concatArrays, pushArray: pushArray, invertMap: invertMap, charMap: charMap, getSingleAttribute: getSingleAttribute, setSingleAttribute: setSingleAttribute, isWhiteSpace: isWhiteSpace, stableSort: stableSort }; /***/ }), /***/ 807: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var _excluded = ["modules"]; function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var s = Object.getOwnPropertySymbols(e); for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; } function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.includes(n)) continue; t[n] = r[n]; } return t; } function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } var DocUtils = __webpack_require__(207); DocUtils.traits = __webpack_require__(536); DocUtils.moduleWrapper = __webpack_require__(899); var createScope = __webpack_require__(779); var Lexer = __webpack_require__(263); var commonModule = __webpack_require__(438); function deprecatedMessage(obj, message) { if (obj.hideDeprecations === true) { return; } // eslint-disable-next-line no-console console.warn(message); } function deprecatedMethod(obj, method) { if (obj.hideDeprecations === true) { return; } return deprecatedMessage(obj, "Deprecated method \".".concat(method, "\", view upgrade guide : https://docxtemplater.com/docs/api/#upgrade-guide, stack : ").concat(new Error().stack)); } var _require = __webpack_require__(946), throwMultiError = _require.throwMultiError, throwResolveBeforeCompile = _require.throwResolveBeforeCompile, throwRenderInvalidTemplate = _require.throwRenderInvalidTemplate, throwRenderTwice = _require.throwRenderTwice, XTInternalError = _require.XTInternalError, throwFileTypeNotIdentified = _require.throwFileTypeNotIdentified, throwFileTypeNotHandled = _require.throwFileTypeNotHandled, throwApiVersionError = _require.throwApiVersionError; var logErrors = __webpack_require__(460); var collectContentTypes = __webpack_require__(891); var getDefaults = DocUtils.getDefaults, str2xml = DocUtils.str2xml, xml2str = DocUtils.xml2str, moduleWrapper = DocUtils.moduleWrapper, concatArrays = DocUtils.concatArrays, uniq = DocUtils.uniq, getDuplicates = DocUtils.getDuplicates, stableSort = DocUtils.stableSort, pushArray = DocUtils.pushArray; var ctXML = "[Content_Types].xml"; var relsFile = "_rels/.rels"; var currentModuleApiVersion = [3, 43, 0]; function dropUnsupportedFileTypesModules(doc) { doc.modules = doc.modules.filter(function (module) { if (!module.supportedFileTypes) { return true; } if (!Array.isArray(module.supportedFileTypes)) { throw new Error("The supportedFileTypes field of the module must be an array"); } var isSupportedModule = module.supportedFileTypes.includes(doc.fileType); if (!isSupportedModule) { module.on("detached"); } return isSupportedModule; }); } function verifyErrors(doc) { var compiled = doc.compiled; doc.errors = concatArrays(Object.keys(compiled).map(function (name) { return compiled[name].allErrors; })); if (doc.errors.length !== 0) { if (doc.options.errorLogging) { logErrors(doc.errors, doc.options.errorLogging); } throwMultiError(doc.errors); } } var Docxtemplater = /*#__PURE__*/function () { function Docxtemplater(zip) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref$modules = _ref.modules, modules = _ref$modules === void 0 ? [] : _ref$modules, options = _objectWithoutProperties(_ref, _excluded); _classCallCheck(this, Docxtemplater); this.targets = []; this.rendered = false; this.scopeManagers = {}; this.compiled = {}; this.modules = [commonModule()]; this.xmlDocuments = {}; if (arguments.length === 0) { deprecatedMessage(this, "Deprecated docxtemplater constructor with no arguments, view upgrade guide : https://docxtemplater.com/docs/api/#upgrade-guide, stack : ".concat(new Error().stack)); this.hideDeprecations = true; this.setOptions(options); } else { this.hideDeprecations = true; this.setOptions(options); if (!zip || !zip.files || typeof zip.file !== "function") { throw new Error("The first argument of docxtemplater's constructor must be a valid zip file (jszip v2 or pizzip v3)"); } if (!Array.isArray(modules)) { throw new Error("The modules argument of docxtemplater's constructor must be an array"); } for (var _i2 = 0; _i2 < modules.length; _i2++) { var _module = modules[_i2]; this.attachModule(_module); } this.loadZip(zip); this.compile(); this.v4Constructor = true; } this.hideDeprecations = false; } return _createClass(Docxtemplater, [{ key: "verifyApiVersion", value: function verifyApiVersion(neededVersion) { neededVersion = neededVersion.split(".").map(function (i) { return parseInt(i, 10); }); if (neededVersion.length !== 3) { throwApiVersionError("neededVersion is not a valid version", { neededVersion: neededVersion, explanation: "the neededVersion must be an array of length 3" }); } if (neededVersion[0] !== currentModuleApiVersion[0]) { throwApiVersionError("The major api version do not match, you probably have to update docxtemplater with npm install --save docxtemplater", { neededVersion: neededVersion, currentModuleApiVersion: currentModuleApiVersion, explanation: "moduleAPIVersionMismatch : needed=".concat(neededVersion.join("."), ", current=").concat(currentModuleApiVersion.join(".")) }); } if (neededVersion[1] > currentModuleApiVersion[1]) { throwApiVersionError("The minor api version is not uptodate, you probably have to update docxtemplater with npm install --save docxtemplater", { neededVersion: neededVersion, currentModuleApiVersion: currentModuleApiVersion, explanation: "moduleAPIVersionMismatch : needed=".concat(neededVersion.join("."), ", current=").concat(currentModuleApiVersion.join(".")) }); } if (neededVersion[1] === currentModuleApiVersion[1] && neededVersion[2] > currentModuleApiVersion[2]) { throwApiVersionError("The patch api version is not uptodate, you probably have to update docxtemplater with npm install --save docxtemplater", { neededVersion: neededVersion, currentModuleApiVersion: currentModuleApiVersion, explanation: "moduleAPIVersionMismatch : needed=".concat(neededVersion.join("."), ", current=").concat(currentModuleApiVersion.join(".")) }); } return true; } }, { key: "setModules", value: function setModules(obj) { for (var _i4 = 0, _this$modules2 = this.modules; _i4 < _this$modules2.length; _i4++) { var _module2 = _this$modules2[_i4]; _module2.set(obj); } } }, { key: "sendEvent", value: function sendEvent(eventName) { for (var _i6 = 0, _this$modules4 = this.modules; _i6 < _this$modules4.length; _i6++) { var _module3 = _this$modules4[_i6]; _module3.on(eventName); } } }, { key: "attachModule", value: function attachModule(module) { if (this.v4Constructor) { throw new XTInternalError("attachModule() should not be called manually when using the v4 constructor"); } deprecatedMethod(this, "attachModule"); var moduleType = _typeof(module); if (moduleType === "function") { throw new XTInternalError("Cannot attach a class/function as a module. Most probably you forgot to instantiate the module by using `new` on the module."); } if (!module || moduleType !== "object") { throw new XTInternalError("Cannot attachModule with a falsy value"); } if (module.requiredAPIVersion) { this.verifyApiVersion(module.requiredAPIVersion); } if (module.attached === true) { if (typeof module.clone === "function") { module = module.clone(); } else { throw new Error("Cannot attach a module that was already attached : \"".concat(module.name, "\". The most likely cause is that you are instantiating the module at the root level, and using it for multiple instances of Docxtemplater")); } } module.attached = true; var wrappedModule = moduleWrapper(module); this.modules.push(wrappedModule); wrappedModule.on("attached"); if (this.fileType) { dropUnsupportedFileTypesModules(this); } return this; } }, { key: "setOptions", value: function setOptions(options) { if (this.v4Constructor) { throw new Error("setOptions() should not be called manually when using the v4 constructor"); } deprecatedMethod(this, "setOptions"); if (!options) { throw new Error("setOptions should be called with an object as first parameter"); } this.options = {}; var defaults = getDefaults(); for (var key in defaults) { var defaultValue = defaults[key]; this.options[key] = options[key] != null ? options[key] : this[key] || defaultValue; this[key] = this.options[key]; } this.delimiters.start = DocUtils.utf8ToWord(this.delimiters.start); this.delimiters.end = DocUtils.utf8ToWord(this.delimiters.end); return this; } }, { key: "loadZip", value: function loadZip(zip) { if (this.v4Constructor) { throw new Error("loadZip() should not be called manually when using the v4 constructor"); } deprecatedMethod(this, "loadZip"); if (zip.loadAsync) { throw new XTInternalError("Docxtemplater doesn't handle JSZip version >=3, please use pizzip"); } this.zip = zip; this.updateFileTypeConfig(); this.modules = concatArrays([this.fileTypeConfig.baseModules.map(function (moduleFunction) { return moduleFunction(); }), this.modules]); for (var _i8 = 0, _this$modules6 = this.modules; _i8 < _this$modules6.length; _i8++) { var _module4 = _this$modules6[_i8]; _module4.zip = this.zip; _module4.docxtemplater = this; } dropUnsupportedFileTypesModules(this); return this; } }, { key: "precompileFile", value: function precompileFile(fileName) { var currentFile = this.createTemplateClass(fileName); currentFile.preparse(); this.compiled[fileName] = currentFile; } }, { key: "compileFile", value: function compileFile(fileName) { this.compiled[fileName].parse(); } }, { key: "getScopeManager", value: function getScopeManager(to, currentFile, tags) { var _this$scopeManagers; (_this$scopeManagers = this.scopeManagers)[to] || (_this$scopeManagers[to] = createScope({ tags: tags, parser: this.parser, cachedParsers: currentFile.cachedParsers })); return this.scopeManagers[to]; } }, { key: "resolveData", value: function resolveData(data) { var _this = this; deprecatedMethod(this, "resolveData"); var errors = []; if (!Object.keys(this.compiled).length) { throwResolveBeforeCompile(); } return Promise.resolve(data).then(function (data) { _this.data = data; _this.setModules({ data: _this.data, Lexer: Lexer }); _this.mapper = _this.modules.reduce(function (value, module) { return module.getRenderedMap(value); }, {}); return Promise.all(Object.keys(_this.mapper).map(function (to) { var _this$mapper$to = _this.mapper[to], from = _this$mapper$to.from, data = _this$mapper$to.data; return Promise.resolve(data).then(function (data) { var currentFile = _this.compiled[from]; currentFile.filePath = to; currentFile.scopeManager = _this.getScopeManager(to, currentFile, data); return currentFile.resolveTags(data).then(function (result) { currentFile.scopeManager.finishedResolving = true; return result; }, function (errs) { Array.prototype.push.apply(errors, errs); }); }); })).then(function (resolved) { if (errors.length !== 0) { if (_this.options.errorLogging) { logErrors(errors, _this.options.errorLogging); } throwMultiError(errors); } return concatArrays(resolved); }); }); } }, { key: "reorderModules", value: function reorderModules() { /** * Modules will be sorted according to priority. * * Input example: * [ * { priority: 1, name: "FooMod" }, * { priority: -1, name: "XMod" }, * { priority: 4, name: "OtherMod" } * ] * * Output example (sorted by priority in descending order): * [ * { priority: 4, name: "OtherMod" }, * { priority: 1, name: "FooMod" }, * { priority: -1, name: "XMod" } * ] */ this.modules = stableSort(this.modules, function (m1, m2) { return (m2.priority || 0) - (m1.priority || 0); }); } }, { key: "throwIfDuplicateModules", value: function throwIfDuplicateModules() { var duplicates = getDuplicates(this.modules.map(function (_ref2) { var name = _ref2.name; return name; })); if (duplicates.length > 0) { throw new XTInternalError("Detected duplicate module \"".concat(duplicates[0], "\"")); } } }, { key: "compile", value: function compile() { var _this2 = this; deprecatedMethod(this, "compile"); this.updateFileTypeConfig(); this.throwIfDuplicateModules(); this.reorderModules(); if (Object.keys(this.compiled).length) { return this; } this.options = this.modules.reduce(function (options, module) { return module.optionsTransformer(options, _this2); }, this.options); this.options.xmlFileNames = uniq(this.options.xmlFileNames); for (var _i10 = 0, _this$options$xmlFile2 = this.options.xmlFileNames; _i10 < _this$options$xmlFile2.length; _i10++) { var fileName = _this$options$xmlFile2[_i10]; var content = this.zip.files[fileName].asText(); this.xmlDocuments[fileName] = str2xml(content); } this.setModules({ zip: this.zip, xmlDocuments: this.xmlDocuments }); this.getTemplatedFiles(); // Loop inside all templatedFiles (ie xml files with content). // Sometimes they don't exist (footer.xml for example) for (var _i12 = 0, _this$templatedFiles2 = this.templatedFiles; _i12 < _this$templatedFiles2.length; _i12++) { var _fileName = _this$templatedFiles2[_i12]; if (this.zip.files[_fileName] != null) { this.precompileFile(_fileName); } } for (var _i14 = 0, _this$templatedFiles4 = this.templatedFiles; _i14 < _this$templatedFiles4.length; _i14++) { var _fileName2 = _this$templatedFiles4[_i14]; if (this.zip.files[_fileName2] != null) { this.compileFile(_fileName2); } } this.setModules({ compiled: this.compiled }); verifyErrors(this); return this; } }, { key: "getRelsTypes", value: function getRelsTypes() { var rootRels = this.zip.files[relsFile]; var rootRelsXml = rootRels ? str2xml(rootRels.asText()) : null; var rootRelationships = rootRelsXml ? rootRelsXml.getElementsByTagName("Relationship") : []; var relsTypes = {}; for (var _i16 = 0; _i16 < rootRelationships.length; _i16++) { var relation = rootRelationships[_i16]; relsTypes[relation.getAttribute("Target")] = relation.getAttribute("Type"); } return relsTypes; } }, { key: "getContentTypes", value: function getContentTypes() { var contentTypes = this.zip.files[ctXML]; var contentTypeXml = contentTypes ? str2xml(contentTypes.asText()) : null; var overrides = contentTypeXml ? contentTypeXml.getElementsByTagName("Override") : null; var defaults = contentTypeXml ? contentTypeXml.getElementsByTagName("Default") : null; return { overrides: overrides, defaults: defaults, contentTypes: contentTypes, contentTypeXml: contentTypeXml }; } }, { key: "updateFileTypeConfig", value: function updateFileTypeConfig() { var fileType; if (this.zip.files.mimetype) { fileType = "odt"; } this.relsTypes = this.getRelsTypes(); var _this$getContentTypes = this.getContentTypes(), overrides = _this$getContentTypes.overrides, defaults = _this$getContentTypes.defaults, contentTypes = _this$getContentTypes.contentTypes, contentTypeXml = _this$getContentTypes.contentTypeXml; if (contentTypeXml) { this.filesContentTypes = collectContentTypes(overrides, defaults, this.zip); this.invertedContentTypes = DocUtils.invertMap(this.filesContentTypes); this.setModules({ contentTypes: this.contentTypes, invertedContentTypes: this.invertedContentTypes }); } for (var _i18 = 0, _this$modules8 = this.modules; _i18 < _this$modules8.length; _i18++) { var _module5 = _this$modules8[_i18]; fileType = _module5.getFileType({ zip: this.zip, contentTypes: contentTypes, contentTypeXml: contentTypeXml, overrides: overrides, defaults: defaults, doc: this }) || fileType; } if (fileType === "odt") { throwFileTypeNotHandled(fileType); } if (!fileType) { throwFileTypeNotIdentified(this.zip); } for (var _i20 = 0, _this$modules10 = this.modules; _i20 < _this$modules10.length; _i20++) { var _module6 = _this$modules10[_i20]; for (var _i22 = 0, _ref4 = _module6.xmlContentTypes || []; _i22 < _ref4.length; _i22++) { var contentType = _ref4[_i22]; pushArray(this.options.xmlFileNames, this.invertedContentTypes[contentType] || []); } } this.fileType = fileType; dropUnsupportedFileTypesModules(this); this.fileTypeConfig = this.options.fileTypeConfig || this.fileTypeConfig || Docxtemplater.FileTypeConfig[this.fileType](); return this; } }, { key: "renderAsync", value: function renderAsync(data) { var _this3 = this; this.hideDeprecations = true; var promise = this.resolveData(data); this.hideDeprecations = false; return promise.then(function () { return _this3.render(); }); } }, { key: "render", value: function render(data) { if (this.rendered) { throwRenderTwice(); } this.rendered = true; if (Object.keys(this.compiled).length === 0) { this.compile(); } if (this.errors.length > 0) { throwRenderInvalidTemplate(); } if (arguments.length > 0) { this.data = data; } this.setModules({ data: this.data, Lexer: Lexer }); this.mapper || (this.mapper = this.modules.reduce(function (value, module) { return module.getRenderedMap(value); }, {})); var output = []; for (var to in this.mapper) { var _this$mapper$to2 = this.mapper[to], from = _this$mapper$to2.from, _data = _this$mapper$to2.data; var currentFile = this.compiled[from]; currentFile.scopeManager = this.getScopeManager(to, currentFile, _data); currentFile.render(to); output.push([to, currentFile.content, currentFile]); delete currentFile.content; } for (var _i24 = 0; _i24 < output.length; _i24++) { var outputPart = output[_i24]; var _outputPart = _slicedToArray(outputPart, 3), content = _outputPart[1], _currentFile = _outputPart[2]; for (var _i26 = 0, _this$modules12 = this.modules; _i26 < _this$modules12.length; _i26++) { var _module7 = _this$modules12[_i26]; if (_module7.preZip) { var result = _module7.preZip(content, _currentFile); if (typeof result === "string") { outputPart[1] = result; } } } } for (var _i28 = 0; _i28 < output.length; _i28++) { var _output$_i = _slicedToArray(output[_i28], 2), _to = _output$_i[0], _content = _output$_i[1]; this.zip.file(_to, _content, { createFolders: true }); } verifyErrors(this); this.sendEvent("syncing-zip"); this.syncZip(); // The synced-zip event is used in the subtemplate module for example this.sendEvent("synced-zip"); return this; } }, { key: "syncZip", value: function syncZip() { for (var fileName in this.xmlDocuments) { this.zip.remove(fileName); var content = xml2str(this.xmlDocuments[fileName]); this.zip.file(fileName, content, { createFolders: true }); } } }, { key: "setData", value: function setData(data) { deprecatedMethod(this, "setData"); this.data = data; return this; } }, { key: "getZip", value: function getZip() { return this.zip; } }, { key: "createTemplateClass", value: function createTemplateClass(path) { var content = this.zip.files[path].asText(); return this.createTemplateClassFromContent(content, path); } }, { key: "createTemplateClassFromContent", value: function createTemplateClassFromContent(content, filePath) { var xmltOptions = { filePath: filePath, contentType: this.filesContentTypes[filePath], relsType: this.relsTypes[filePath] }; var defaults = getDefaults(); var defaultKeys = pushArray(Object.keys(defaults), ["filesContentTypes", "fileTypeConfig", "fileType", "modules"]); for (var _i30 = 0; _i30 < defaultKeys.length; _i30++) { var key = defaultKeys[_i30]; xmltOptions[key] = this[key]; } return new Docxtemplater.XmlTemplater(content, xmltOptions); } }, { key: "getFullText", value: function getFullText(path) { return this.createTemplateClass(path || this.fileTypeConfig.textPath(this)).getFullText(); } }, { key: "getTemplatedFiles", value: function getTemplatedFiles() { this.templatedFiles = this.fileTypeConfig.getTemplatedFiles(this.zip); pushArray(this.templatedFiles, this.targets); this.templatedFiles = uniq(this.templatedFiles); return this.templatedFiles; } }]); }(); Docxtemplater.DocUtils = DocUtils; Docxtemplater.Errors = __webpack_require__(946); Docxtemplater.XmlTemplater = __webpack_require__(245); Docxtemplater.FileTypeConfig = __webpack_require__(271); Docxtemplater.XmlMatcher = __webpack_require__(367); module.exports = Docxtemplater; module.exports["default"] = Docxtemplater; /***/ }), /***/ 460: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { var _require = __webpack_require__(207), pushArray = _require.pushArray; // The error thrown here contains additional information when logged with JSON.stringify (it contains a properties object containing all suberrors). function replaceErrors(key, value) { if (value instanceof Error) { return pushArray(Object.getOwnPropertyNames(value), ["stack"]).reduce(function (error, key) { error[key] = value[key]; if (key === "stack") { // This is used because in Firefox, stack is not an own property error[key] = value[key].toString(); } return error; }, {}); } return value; } function logger(error, logging) { // eslint-disable-next-line no-console console.log(JSON.stringify({ error: error }, replaceErrors, logging === "json" ? 2 : null)); if (error.properties && error.properties.errors instanceof Array) { var errorMessages = error.properties.errors.map(function (error) { return error.properties.explanation; }).join("\n"); // eslint-disable-next-line no-console console.log("errorMessages", errorMessages); // errorMessages is a humanly readable message looking like this : // 'The tag beginning with "foobar" is unopened' } } module.exports = logger; /***/ }), /***/ 946: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } var _require = __webpack_require__(320), last = _require.last, first = _require.first; function XTError(message) { this.name = "GenericError"; this.message = message; this.stack = new Error(message).stack; } XTError.prototype = Error.prototype; function XTTemplateError(message) { this.name = "TemplateError"; this.message = message; this.stack = new Error(message).stack; } XTTemplateError.prototype = new XTError(); function XTRenderingError(message) { this.name = "RenderingError"; this.message = message; this.stack = new Error(message).stack; } XTRenderingError.prototype = new XTError(); function XTScopeParserError(message) { this.name = "ScopeParserError"; this.message = message; this.stack = new Error(message).stack; } XTScopeParserError.prototype = new XTError(); function XTInternalError(message) { this.name = "InternalError"; this.properties = { explanation: "InternalError" }; this.message = message; this.stack = new Error(message).stack; } XTInternalError.prototype = new XTError(); function XTAPIVersionError(message) { this.name = "APIVersionError"; this.properties = { explanation: "APIVersionError" }; this.message = message; this.stack = new Error(message).stack; } XTAPIVersionError.prototype = new XTError(); function throwApiVersionError(msg, properties) { var err = new XTAPIVersionError(msg); err.properties = _objectSpread({ id: "api_version_error" }, properties); throw err; } function throwMultiError(errors) { var err = new XTTemplateError("Multi error"); err.properties = { errors: errors, id: "multi_error", explanation: "The template has multiple errors" }; throw err; } function getUnopenedTagException(options) { var err = new XTTemplateError("Unopened tag"); err.properties = { xtag: last(options.xtag.split(" ")), id: "unopened_tag", context: options.xtag, offset: options.offset, lIndex: options.lIndex, explanation: "The tag beginning with \"".concat(options.xtag.substr(0, 10), "\" is unopened") }; return err; } function getDuplicateOpenTagException(options) { var err = new XTTemplateError("Duplicate open tag, expected one open tag"); err.properties = { xtag: first(options.xtag.split(" ")), id: "duplicate_open_tag", context: options.xtag, offset: options.offset, lIndex: options.lIndex, explanation: "The tag beginning with \"".concat(options.xtag.substr(0, 10), "\" has duplicate open tags") }; return err; } function getDuplicateCloseTagException(options) { var err = new XTTemplateError("Duplicate close tag, expected one close tag"); err.properties = { xtag: first(options.xtag.split(" ")), id: "duplicate_close_tag", context: options.xtag, offset: options.offset, lIndex: options.lIndex, explanation: "The tag ending with \"".concat(options.xtag.substr(0, 10), "\" has duplicate close tags") }; return err; } function getUnclosedTagException(options) { var err = new XTTemplateError("Unclosed tag"); err.properties = { xtag: first(options.xtag.split(" ")).substr(1), id: "unclosed_tag", context: options.xtag, offset: options.offset, lIndex: options.lIndex, explanation: "The tag beginning with \"".concat(options.xtag.substr(0, 10), "\" is unclosed") }; return err; } function throwXmlTagNotFound(options) { var err = new XTTemplateError("No tag \"".concat(options.element, "\" was found at the ").concat(options.position)); var part = options.parsed[options.index]; err.properties = { id: "no_xml_tag_found_at_".concat(options.position), explanation: "No tag \"".concat(options.element, "\" was found at the ").concat(options.position), offset: part.offset, part: part, parsed: options.parsed, index: options.index, element: options.element }; throw err; } function getCorruptCharactersException(_ref) { var tag = _ref.tag, value = _ref.value, offset = _ref.offset; var err = new XTRenderingError("There are some XML corrupt characters"); err.properties = { id: "invalid_xml_characters", xtag: tag, value: value, offset: offset, explanation: "There are some corrupt characters for the field ".concat(tag) }; return err; } function getInvalidRawXMLValueException(_ref2) { var tag = _ref2.tag, value = _ref2.value, offset = _ref2.offset; var err = new XTRenderingError("Non string values are not allowed for rawXML tags"); err.properties = { id: "invalid_raw_xml_value", xtag: tag, value: value, offset: offset, explanation: "The value of the raw tag : '".concat(tag, "' is not a string") }; return err; } function throwExpandNotFound(options) { var _options$part = options.part, value = _options$part.value, offset = _options$part.offset, _options$id = options.id, id = _options$id === void 0 ? "raw_tag_outerxml_invalid" : _options$id, _options$message = opti