mammoth-style
Version:
Convert Word documents (.docx files) to HTML (with style)
2 lines • 563 kB
JavaScript
!function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{var g;g="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,g.mammoth=f()}}(function(){var define,module,exports;return function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r}()({1:[function(require,module,exports){function Files(){function read(uri){return promises.reject(new Error("could not open external image: '"+uri+"'\ncannot open linked files from a web browser"))}return{read:read}}var promises=require("../../lib/promises");exports.Files=Files},{"../../lib/promises":24}],2:[function(require,module,exports){function openZip(options){return options.arrayBuffer?promises.resolve(zipfile.openArrayBuffer(options.arrayBuffer)):promises.reject(new Error("Could not find file in options"))}var promises=require("../lib/promises"),zipfile=require("../lib/zipfile");exports.openZip=openZip},{"../lib/promises":24,"../lib/zipfile":36}],3:[function(require,module,exports){function paragraph(options){return new Matcher("paragraph",options)}function run(options){return new Matcher("run",options)}function Matcher(elementType,options){options=options||{},this._elementType=elementType,this._styleId=options.styleId,this._styleName=options.styleName,options.list&&(this._listIndex=options.list.levelIndex,this._listIsOrdered=options.list.isOrdered)}function isList(element,levelIndex,isOrdered){return element.numbering&&element.numbering.level==levelIndex&&element.numbering.isOrdered==isOrdered}exports.paragraph=paragraph,exports.run=run,exports.bold=new Matcher("bold"),exports.italic=new Matcher("italic"),exports.underline=new Matcher("underline"),exports.strikethrough=new Matcher("strikethrough"),exports.commentReference=new Matcher("commentReference"),Matcher.prototype.matches=function(element){return element.type===this._elementType&&(void 0===this._styleId||element.styleId===this._styleId)&&(void 0===this._styleName||element.styleName&&element.styleName.toUpperCase()===this._styleName.toUpperCase())&&(void 0===this._listIndex||isList(element,this._listIndex,this._listIsOrdered))}},{}],4:[function(require,module,exports){function DocumentConverter(options){return{convertToHtml:function(element){var comments=_.indexBy(element.type===documents.types.document?element.comments:[],"commentId"),conversion=new DocumentConversion(options,comments);return conversion.convertToHtml(element)}}}function DocumentConversion(options,comments){function convertToHtml(document){var messages=[],html=elementToHtml(document,messages),deferredNodes=[];walkHtml(html,function(node){"deferred"===node.type&&deferredNodes.push(node)});var deferredValues={};return promises.mapSeries(deferredNodes,function(deferred){return deferred.value().then(function(value){deferredValues[deferred.id]=value})}).then(function(){function replaceDeferred(nodes){return flatMap(nodes,function(node){return"deferred"===node.type?deferredValues[node.id]:node.children?[_.extend({},node,{children:replaceDeferred(node.children)})]:[node]})}var writer=writers.writer({prettyPrint:options.prettyPrint,outputFormat:options.outputFormat});return Html.write(writer,Html.simplify(replaceDeferred(html))),new results.Result(writer.asString(),messages)})}function convertElements(elements,messages){return flatMap(elements,function(element){return elementToHtml(element,messages)})}function elementToHtml(element,messages){var handler=elementConverters[element.type];return handler?handler(element,messages):[]}function convertParagraph(element,messages){return htmlPathForParagraph(element,messages).wrap(function(){var content=convertElements(element.children,messages);return options.ignoreEmptyParagraphs?content:[Html.forceWrite].concat(content)})}function htmlPathForParagraph(element,messages){var style=findStyle(element),listTypes={decimal:"1",upperRoman:"I",lowerRoman:"i",upperLetter:"A",lowerLetter:"a"};if(style){var style_clone=clone(style);for(var i in style_clone.to._elements)"ol"==style_clone.to._elements[i].tagName&&element.numbering&&element.numbering.format&&(style_clone.to._elements[i].attributes.type=listTypes[element.numbering.format]);return style_clone.to}return element.styleId&&messages.push(unrecognisedStyleWarning("paragraph",element)),defaultParagraphStyle}function convertRun(run,messages){var nodes=function(){return convertElements(run.children,messages)},paths=[];run.isStrikethrough&&paths.push(findHtmlPathForRunProperty("strikethrough","s")),run.isUnderline&&paths.push(findHtmlPathForRunProperty("underline")),run.verticalAlignment===documents.verticalAlignment.subscript&&paths.push(htmlPaths.element("sub",{},{fresh:!1})),run.verticalAlignment===documents.verticalAlignment.superscript&&paths.push(htmlPaths.element("sup",{},{fresh:!1})),run.isItalic&&paths.push(findHtmlPathForRunProperty("italic","em")),run.isBold&&paths.push(findHtmlPathForRunProperty("bold","strong")),run.color&&paths.push(htmlPaths.element("font",{color:run.color},{fresh:!1}));var stylePath=htmlPaths.empty;if(run.styleId){var style=findStyle(run);style?stylePath=style.to:messages.push(unrecognisedStyleWarning("run",run))}return paths.push(stylePath),paths.forEach(function(path){nodes=path.wrap.bind(path,nodes)}),nodes()}function findHtmlPathForRunProperty(elementType,defaultTagName){var path=findHtmlPath({type:elementType});return path?path:defaultTagName?htmlPaths.element(defaultTagName,{},{fresh:!1}):htmlPaths.empty}function findHtmlPath(element,defaultPath){var style=findStyle(element);return style?style.to:defaultPath}function findStyle(element){for(var i=0;i<styleMap.length;i++)if(styleMap[i].from.matches(element))return styleMap[i]}function recoveringConvertImage(convertImage){return function(image,messages){return convertImage(image,messages).caught(function(error){return messages.push(results.warning(error.message)),[]})}}function noteHtmlId(note){return referentHtmlId(note.noteType,note.noteId)}function noteRefHtmlId(note){return referenceHtmlId(note.noteType,note.noteId)}function referentHtmlId(referenceType,referenceId){return htmlId(referenceType+"-"+referenceId)}function referenceHtmlId(referenceType,referenceId){return htmlId(referenceType+"-ref-"+referenceId)}function htmlId(suffix){return idPrefix+suffix}function convertTable(element,messages){return wrapChildrenInFreshElement(element,"table",messages)}function convertTableRow(element,messages){return wrapChildrenInFreshElement(element,"tr",messages)}function convertTableCell(element,messages){var children=convertElements(element.children,messages),attributes={};return 1!==element.colSpan&&(attributes.colspan=element.colSpan.toString()),1!==element.rowSpan&&(attributes.rowspan=element.rowSpan.toString()),[Html.freshElement("td",attributes,[Html.forceWrite].concat(children))]}function convertCommentReference(reference,messages){return findHtmlPath(reference,htmlPaths.ignore).wrap(function(){var comment=comments[reference.commentId],count=referencedComments.length+1,label="["+commentAuthorLabel(comment)+count+"]";return referencedComments.push({label:label,comment:comment}),[Html.freshElement("a",{href:"#"+referentHtmlId("comment",reference.commentId),id:referenceHtmlId("comment",reference.commentId)},[Html.text(label)])]})}function convertComment(referencedComment,messages){var label=referencedComment.label,comment=referencedComment.comment,body=convertElements(comment.body).concat([Html.nonFreshElement("p",{},[Html.text(" "),Html.freshElement("a",{href:"#"+referenceHtmlId("comment",comment.commentId)},[Html.text("↑")])])]);return[Html.freshElement("dt",{id:referentHtmlId("comment",comment.commentId)},[Html.text("Comment "+label)]),Html.freshElement("dd",{},body)]}function wrapChildrenInFreshElement(element,wrapElementName,messages){var children=convertElements(element.children,messages);return[Html.freshElement(wrapElementName,{},[Html.forceWrite].concat(children))]}var noteNumber=1,noteReferences=[],referencedComments=[];options=_.extend({ignoreEmptyParagraphs:!0},options);var idPrefix=void 0===options.idPrefix?"":options.idPrefix,defaultParagraphStyle=htmlPaths.topLevelElement("p"),styleMap=options.styleMap||[],defaultConvertImage=images.imgElement(function(element){return element.read("base64").then(function(imageBuffer){return{src:"data:"+element.contentType+";base64,"+imageBuffer}})}),elementConverters={document:function(document,messages){var children=convertElements(document.children,messages),notes=noteReferences.map(function(noteReference){return document.notes.resolve(noteReference)}),notesNodes=convertElements(notes,messages);return children.concat([Html.freshElement("ol",{},notesNodes),Html.freshElement("dl",{},flatMap(referencedComments,function(referencedComment){return convertComment(referencedComment,messages)}))])},paragraph:convertParagraph,run:convertRun,text:function(element,messages){return[Html.text(element.value)]},tab:function(element,messages){return[Html.text(" ")]},hyperlink:function(element,messages){var href=element.anchor?"#"+htmlId(element.anchor):element.href,children=convertElements(element.children,messages);return[Html.freshElement("a",{href:href},children)]},bookmarkStart:function(element,messages){var anchor=Html.freshElement("a",{id:htmlId(element.name)},[Html.forceWrite]);return[anchor]},noteReference:function(element,messages){noteReferences.push(element);var anchor=Html.freshElement("a",{href:"#"+noteHtmlId(element),id:noteRefHtmlId(element)},[Html.text("["+noteNumber++ +"]")]);return[Html.freshElement("sup",{},[anchor])]},note:function(element,messages){var children=convertElements(element.body,messages),backLink=Html.elementWithTag(htmlPaths.element("p",{},{fresh:!1}),[Html.text(" "),Html.freshElement("a",{href:"#"+noteRefHtmlId(element)},[Html.text("↑")])]),body=children.concat([backLink]);return Html.freshElement("li",{id:noteHtmlId(element)},body)},commentReference:convertCommentReference,comment:convertComment,image:deferredConversion(recoveringConvertImage(options.convertImage||defaultConvertImage)),table:convertTable,tableRow:convertTableRow,tableCell:convertTableCell,lineBreak:function(element,messages){return[Html.selfClosingElement("br")]}};return{convertToHtml:convertToHtml}}function deferredConversion(func){return function(element,messages){return[{type:"deferred",id:deferredId++,value:function(){return func(element,messages)}}]}}function unrecognisedStyleWarning(type,element){return results.warning("Unrecognised "+type+" style: '"+element.styleName+"' (Style ID: "+element.styleId+")")}function flatMap(values,func){return _.flatten(values.map(func),!0)}function walkHtml(nodes,callback){nodes.forEach(function(node){callback(node),node.children&&walkHtml(node.children,callback)})}var _=require("underscore"),promises=require("./promises"),documents=require("./documents"),htmlPaths=require("./html-paths"),results=require("./results"),images=require("./images"),Html=require("./html"),writers=require("./writers"),clone=require("clone");exports.DocumentConverter=DocumentConverter;var deferredId=1,commentAuthorLabel=exports.commentAuthorLabel=function(comment){return comment.authorInitials||""}},{"./documents":5,"./html":19,"./html-paths":17,"./images":21,"./promises":24,"./results":25,"./writers":30,clone:75,underscore:215}],5:[function(require,module,exports){function Document(children,options){return options=options||{},{type:types.document,children:children,notes:options.notes||new Notes({}),comments:options.comments||[]}}function Paragraph(children,properties){return properties=properties||{},{type:types.paragraph,children:children,styleId:properties.styleId||null,styleName:properties.styleName||null,numbering:properties.numbering||null,alignment:properties.alignment||null}}function Run(children,properties){return properties=properties||{},{type:types.run,children:children,styleId:properties.styleId||null,styleName:properties.styleName||null,isBold:properties.isBold,isUnderline:properties.isUnderline,isItalic:properties.isItalic,isStrikethrough:properties.isStrikethrough,verticalAlignment:properties.verticalAlignment||verticalAlignment.baseline,color:properties.color}}function Text(value){return{type:types.text,value:value}}function Tab(){return{type:types.tab}}function Hyperlink(children,options){return{type:types.hyperlink,children:children,href:options.href,anchor:options.anchor}}function NoteReference(options){return{type:types.noteReference,noteType:options.noteType,noteId:options.noteId}}function Notes(notes){this._notes=_.indexBy(notes,function(note){return noteKey(note.noteType,note.noteId)})}function Note(options){return{type:types.note,noteType:options.noteType,noteId:options.noteId,body:options.body}}function commentReference(options){return{type:types.commentReference,commentId:options.commentId}}function comment(options){return{type:types.comment,commentId:options.commentId,body:options.body,authorName:options.authorName,authorInitials:options.authorInitials}}function noteKey(noteType,id){return noteType+"-"+id}function Image(options){return{type:types.image,read:options.readImage,altText:options.altText,contentType:options.contentType}}function Table(children){return{type:types.table,children:children}}function TableRow(children){return{type:types.tableRow,children:children}}function TableCell(children,options){return options=options||{},{type:types.tableCell,children:children,colSpan:null==options.colSpan?1:options.colSpan,rowSpan:null==options.rowSpan?1:options.rowSpan}}function LineBreak(){return{type:types.lineBreak}}function BookmarkStart(options){return{type:types.bookmarkStart,name:options.name}}var _=require("underscore"),types=exports.types={document:"document",paragraph:"paragraph",run:"run",text:"text",tab:"tab",hyperlink:"hyperlink",noteReference:"noteReference",image:"image",note:"note",commentReference:"commentReference",comment:"comment",table:"table",tableRow:"tableRow",tableCell:"tableCell",lineBreak:"lineBreak",bookmarkStart:"bookmarkStart"},verticalAlignment={baseline:"baseline",superscript:"superscript",subscript:"subscript"};Notes.prototype.resolve=function(reference){return this.findNoteByKey(noteKey(reference.noteType,reference.noteId))},Notes.prototype.findNoteByKey=function(key){return this._notes[key]||null},exports.document=exports.Document=Document,exports.paragraph=exports.Paragraph=Paragraph,exports.run=exports.Run=Run,exports.Text=Text,exports.Tab=Tab,exports.Hyperlink=Hyperlink,exports.noteReference=exports.NoteReference=NoteReference,exports.Notes=Notes,exports.Note=Note,exports.commentReference=commentReference,exports.comment=comment,exports.Image=Image,exports.Table=Table,exports.TableRow=TableRow,exports.TableCell=TableCell,exports.LineBreak=LineBreak,exports.BookmarkStart=BookmarkStart,exports.verticalAlignment=verticalAlignment},{underscore:215}],6:[function(require,module,exports){function BodyReader(options){function readXmlElements(elements){var results=elements.map(readXmlElement);return combineResults(results)}function readXmlElement(element){if("element"===element.type){var handler=xmlElementReaders[element.name];if(handler)return handler(element);if(!Object.prototype.hasOwnProperty.call(ignoreElements,element.name)){var message=warning("An unrecognised element was ignored: "+element.name);return emptyResultWithMessages([message])}}return emptyResult()}function readRunProperties(element){var properties={type:"runProperties"},verticalAlignmentElement=element.first("w:vertAlign");return verticalAlignmentElement&&(properties.verticalAlignment=verticalAlignmentElement.attributes["w:val"]),properties.isBold=!!element.first("w:b"),properties.isUnderline=!!element.first("w:u"),properties.isItalic=!!element.first("w:i"),properties.isStrikethrough=!!element.first("w:strike"),properties.color=!1,element.first("w:color")&&(properties.color="#"+element.first("w:color").attributes["w:val"]),readRunStyle(element).map(function(style){return properties.styleId=style.styleId,properties.styleName=style.name,properties})}function readParagraphStyle(element){return readStyle(element,"w:pStyle","Paragraph",styles.findParagraphStyleById)}function readRunStyle(element){return readStyle(element,"w:rStyle","Run",styles.findCharacterStyleById)}function readStyle(element,styleTagName,styleType,findStyleById){var messages=[],styleElement=element.first(styleTagName),styleId=null,name=null;if(styleElement&&(styleId=styleElement.attributes["w:val"])){var style=findStyleById(styleId);style?name=style.name:messages.push(undefinedStyleWarning(styleType,styleId))}return elementResultWithMessages({styleId:styleId,name:name},messages)}function noteReferenceReader(noteType){return function(element){var noteId=element.attributes["w:id"];return elementResult(new documents.NoteReference({noteType:noteType,noteId:noteId}))}}function readCommentReference(element){return elementResult(documents.commentReference({commentId:element.attributes["w:id"]}))}function readChildElements(element){return readXmlElements(element.children)}function readNumberingProperties(element){var level=element.firstOrEmpty("w:ilvl").attributes["w:val"],numId=element.firstOrEmpty("w:numId").attributes["w:val"];return void 0===level||void 0===numId?null:numbering.findLevel(numId,level)}function readTable(element){return readXmlElements(element.children).flatMap(calculateRowSpans).map(documents.Table)}function readTableRow(element){return readXmlElements(element.children).map(documents.TableRow)}function readTableCell(element){return readXmlElements(element.children).map(function(children){var properties=element.firstOrEmpty("w:tcPr"),gridSpan=properties.firstOrEmpty("w:gridSpan").attributes["w:val"],colSpan=gridSpan?parseInt(gridSpan,10):1,cell=documents.TableCell(children,{colSpan:colSpan});return cell._vMerge=readVMerge(properties),cell})}function readVMerge(properties){var element=properties.first("w:vMerge");if(element){var val=element.attributes["w:val"];return"continue"===val||!val}return null}function calculateRowSpans(rows){var unexpectedNonRows=_.any(rows,function(row){return row.type!==documents.types.tableRow});if(unexpectedNonRows)return elementResultWithMessages(rows,[warning("unexpected non-row element in table, cell merging may be incorrect")]);var unexpectedNonCells=_.any(rows,function(row){return _.any(row.children,function(cell){return cell.type!==documents.types.tableCell})});if(unexpectedNonCells)return elementResultWithMessages(rows,[warning("unexpected non-cell element in table row, cell merging may be incorrect")]);var columns={};return rows.forEach(function(row){var cellIndex=0;row.children.forEach(function(cell){cell._vMerge&&columns[cellIndex]?columns[cellIndex].rowSpan++:(columns[cellIndex]=cell,cell._vMerge=!1),cellIndex+=cell.colSpan})}),rows.forEach(function(row){row.children=row.children.filter(function(cell){return!cell._vMerge}),row.children.forEach(function(cell){delete cell._vMerge})}),elementResult(rows)}function readDrawingElement(element){var blips=element.getElementsByTagName("a:graphic").getElementsByTagName("a:graphicData").getElementsByTagName("pic:pic").getElementsByTagName("pic:blipFill").getElementsByTagName("a:blip");return combineResults(blips.map(readBlip.bind(null,element)))}function readBlip(element,blip){var altText=element.first("wp:docPr").attributes.descr;return readImage(findBlipImageFile(blip),altText)}function findBlipImageFile(blip){var embedRelationshipId=blip.attributes["r:embed"],linkRelationshipid=blip.attributes["r:link"];if(embedRelationshipId)return findEmbeddedImageFile(embedRelationshipId);var imagePath=relationships[linkRelationshipid].target;return{path:imagePath,read:files.read.bind(files,imagePath)}}function readImageData(element){return readImage(findEmbeddedImageFile(element.attributes["r:id"]),element.attributes["o:title"])}function findEmbeddedImageFile(relationshipId){var path=joinZipPath("word",relationships[relationshipId].target);return{path:path,read:docxFile.read.bind(docxFile,path)}}function readImage(imageFile,altText){var contentType=contentTypes.findContentType(imageFile.path),image=documents.Image({readImage:imageFile.read,altText:altText,contentType:contentType}),warnings=supportedImageTypes[contentType]?[]:warning("Image of type "+contentType+" is unlikely to display in web browsers");return elementResultWithMessages(image,warnings)}function undefinedStyleWarning(type,styleId){return warning(type+" style with ID "+styleId+" was referenced but not defined in the document")}var relationships=options.relationships,contentTypes=options.contentTypes,docxFile=options.docxFile,files=options.files,numbering=options.numbering,styles=options.styles,xmlElementReaders={"w:p":function(element){return readXmlElements(element.children).map(function(children){var properties=_.find(children,isParagraphProperties);return new documents.Paragraph(children.filter(negate(isParagraphProperties)),properties)}).insertExtra()},"w:pPr":function(element){var properties={type:"paragraphProperties"},alignElement=element.first("w:jc");return alignElement&&(properties.alignment=alignElement.attributes["w:val"]),properties.numbering=readNumberingProperties(element.firstOrEmpty("w:numPr")),readParagraphStyle(element).map(function(style){return properties.styleId=style.styleId,properties.styleName=style.name,properties})},"w:r":function(element){return readXmlElements(element.children).map(function(children){var properties=_.find(children,isRunProperties);return new documents.Run(children.filter(negate(isRunProperties)),properties)})},"w:rPr":readRunProperties,"w:t":function(element){return elementResult(new documents.Text(element.text()))},"w:tab":function(element){return elementResult(new documents.Tab)},"w:hyperlink":function(element){var relationshipId=element.attributes["r:id"],anchor=element.attributes["w:anchor"];return readXmlElements(element.children).map(function(children){if(relationshipId){var href=relationships[relationshipId].target;return new documents.Hyperlink(children,{href:href})}return anchor?new documents.Hyperlink(children,{anchor:anchor}):children})},"w:tbl":readTable,"w:tr":readTableRow,"w:tc":readTableCell,"w:footnoteReference":noteReferenceReader("footnote"),"w:endnoteReference":noteReferenceReader("endnote"),"w:commentReference":readCommentReference,"w:br":function(element){var breakType=element.attributes["w:type"];return breakType?emptyResultWithMessages([warning("Unsupported break type: "+breakType)]):elementResult(new documents.LineBreak)},"w:bookmarkStart":function(element){var name=element.attributes["w:name"];return"_GoBack"===name?emptyResult():elementResult(new documents.BookmarkStart({name:name}))},"mc:AlternateContent":function(element){return readChildElements(element.first("mc:Fallback"))},"w:sdt":function(element){return readXmlElements(element.firstOrEmpty("w:sdtContent").children)},"w:ins":readChildElements,"w:smartTag":readChildElements,"w:drawing":readChildElements,"w:pict":function(element){return readChildElements(element).toExtra()},"v:roundrect":readChildElements,"v:shape":readChildElements,"v:textbox":readChildElements,"w:txbxContent":readChildElements,"wp:inline":readDrawingElement,"wp:anchor":readDrawingElement,"v:imagedata":readImageData,"v:imageData":readImageData};return{readXmlElement:readXmlElement,readXmlElements:readXmlElements,_readNumberingProperties:readNumberingProperties}}function isParagraphProperties(element){return"paragraphProperties"===element.type}function isRunProperties(element){return"runProperties"===element.type}function negate(predicate){return function(value){return!predicate(value)}}function joinZipPath(first,second){return first+"/"+second}function emptyResultWithMessages(messages){return new ReadResult(null,null,messages)}function emptyResult(){return new ReadResult(null)}function elementResult(element){return new ReadResult(element)}function elementResultWithMessages(element,messages){return new ReadResult(element,null,messages)}function ReadResult(element,extra,messages){this.value=element||[],this.extra=extra,this._result=new Result({element:this.value,extra:extra},messages),this.messages=this._result.messages}function combineResults(results){var result=Result.combine(_.pluck(results,"_result"));return new ReadResult(_.flatten(_.pluck(result.value,"element")),_.filter(_.flatten(_.pluck(result.value,"extra")),identity),result.messages)}function joinElements(first,second){return _.flatten([first,second])}function identity(value){return value}exports.BodyReader=BodyReader;var _=require("underscore"),documents=require("../documents"),Result=require("../results").Result,warning=require("../results").warning,supportedImageTypes={"image/png":!0,"image/gif":!0,"image/jpeg":!0,"image/svg+xml":!0,"image/tiff":!0},ignoreElements={"office-word:wrap":!0,"v:shadow":!0,"v:shapetype":!0,"w:annotationRef":!0,"w:bookmarkEnd":!0,"w:sectPr":!0,"w:proofErr":!0,"w:lastRenderedPageBreak":!0,"w:commentRangeStart":!0,"w:commentRangeEnd":!0,"w:del":!0,"w:footnoteRef":!0,"w:endnoteRef":!0,"w:tblPr":!0,"w:tblGrid":!0,"w:tcPr":!0};ReadResult.prototype.toExtra=function(){return new ReadResult(null,joinElements(this.extra,this.value),this.messages)},ReadResult.prototype.insertExtra=function(){var extra=this.extra;return extra&&extra.length?new ReadResult(joinElements(this.value,extra),null,this.messages):this},ReadResult.prototype.map=function(func){var result=this._result.map(function(value){return func(value.element)});return new ReadResult(result.value,this.extra,result.messages)},ReadResult.prototype.flatMap=function(func){var result=this._result.flatMap(function(value){return func(value.element)._result});return new ReadResult(result.value.element,joinElements(this.extra,result.value.extra),result.messages)}},{"../documents":5,"../results":25,underscore:215}],7:[function(require,module,exports){function createCommentsReader(bodyReader){function readCommentsXml(element){return Result.combine(element.getElementsByTagName("w:comment").map(readCommentElement))}function readCommentElement(element){function readOptionalAttribute(name){return(element.attributes[name]||"").trim()||null}var id=element.attributes["w:id"];return bodyReader.readXmlElements(element.children).map(function(body){return documents.comment({commentId:id,body:body,authorName:readOptionalAttribute("w:author"),authorInitials:readOptionalAttribute("w:initials")})})}return readCommentsXml}var documents=require("../documents"),Result=require("../results").Result;exports.createCommentsReader=createCommentsReader},{"../documents":5,"../results":25}],8:[function(require,module,exports){function readContentTypesFromXml(element){var extensionDefaults={},overrides={};return element.children.forEach(function(child){if("content-types:Default"===child.name&&(extensionDefaults[child.attributes.Extension]=child.attributes.ContentType),"content-types:Override"===child.name){var name=child.attributes.PartName;"/"===name.charAt(0)&&(name=name.substring(1)),overrides[name]=child.attributes.ContentType}}),contentTypes(overrides,extensionDefaults)}function contentTypes(overrides,extensionDefaults){return{findContentType:function(path){var overrideContentType=overrides[path];if(overrideContentType)return overrideContentType;var pathParts=path.split("."),extension=pathParts[pathParts.length-1];if(extensionDefaults.hasOwnProperty(extension))return extensionDefaults[extension];var fallback=fallbackContentTypes[extension.toLowerCase()];return fallback?"image/"+fallback:null}}}exports.readContentTypesFromXml=readContentTypesFromXml;var fallbackContentTypes={png:"png",gif:"gif",jpeg:"jpeg",jpg:"jpeg",tif:"tiff",tiff:"tiff",bmp:"bmp"};exports.defaultContentTypes=contentTypes({},{})},{}],9:[function(require,module,exports){function DocumentXmlReader(options){function convertXmlToDocument(element){var body=element.first("w:body"),result=bodyReader.readXmlElements(body.children).map(function(children){return new documents.Document(children,{notes:options.notes,comments:options.comments})});return new Result(result.value,result.messages)}var bodyReader=options.bodyReader;return{convertXmlToDocument:convertXmlToDocument}}exports.DocumentXmlReader=DocumentXmlReader;var documents=require("../documents"),Result=require("../results").Result},{"../documents":5,"../results":25}],10:[function(require,module,exports){function read(docxFile,input){return input=input||{},promises.props({contentTypes:readContentTypesFromZipFile(docxFile),numbering:readNumberingFromZipFile(docxFile),styles:readStylesFromZipFile(docxFile),docxFile:docxFile,files:new Files(input.path?path.dirname(input.path):null)}).also(function(result){return{footnotes:readXmlFileWithBody("footnotes",result,function(bodyReader,xml){return xml?notesReader.createFootnotesReader(bodyReader)(xml):new Result([])}),endnotes:readXmlFileWithBody("endnotes",result,function(bodyReader,xml){return xml?notesReader.createEndnotesReader(bodyReader)(xml):new Result([])}),comments:readXmlFileWithBody("comments",result,function(bodyReader,xml){return xml?commentsReader.createCommentsReader(bodyReader)(xml):new Result([])})}}).also(function(result){return{notes:result.footnotes.flatMap(function(footnotes){return result.endnotes.map(function(endnotes){return new documents.Notes(footnotes.concat(endnotes))})})}}).then(function(result){return readXmlFileWithBody("document",result,function(bodyReader,xml){return result.notes.flatMap(function(notes){return result.comments.flatMap(function(comments){var reader=new DocumentXmlReader({bodyReader:bodyReader,notes:notes,comments:comments});return reader.convertXmlToDocument(xml)})})})})}function xmlFileReader(options){return function(zipFile){return readXmlFromZipFile(zipFile,options.filename).then(function(element){return element?options.readElement(element):options.defaultValue})}}function readXmlFileWithBody(name,options,func){var readRelationshipsFromZipFile=xmlFileReader({filename:"word/_rels/"+name+".xml.rels",readElement:relationshipsReader.readRelationships,defaultValue:{}});return readRelationshipsFromZipFile(options.docxFile).then(function(relationships){var bodyReader=new BodyReader({relationships:relationships,contentTypes:options.contentTypes,docxFile:options.docxFile,numbering:options.numbering,styles:options.styles,files:options.files});return readXmlFromZipFile(options.docxFile,"word/"+name+".xml").then(function(xml){return func(bodyReader,xml)})})}exports.read=read;var path=require("path"),promises=require("../promises"),documents=require("../documents"),Result=require("../results").Result,readXmlFromZipFile=require("./office-xml-reader").readXmlFromZipFile,BodyReader=require("./body-reader").BodyReader,DocumentXmlReader=require("./document-xml-reader").DocumentXmlReader,relationshipsReader=require("./relationships-reader"),contentTypesReader=require("./content-types-reader"),numberingXml=require("./numbering-xml"),stylesReader=require("./styles-reader"),notesReader=require("./notes-reader"),commentsReader=require("./comments-reader"),Files=require("./files").Files,readContentTypesFromZipFile=xmlFileReader({filename:"[Content_Types].xml",readElement:contentTypesReader.readContentTypesFromXml,defaultValue:contentTypesReader.defaultContentTypes}),readNumberingFromZipFile=xmlFileReader({filename:"word/numbering.xml",readElement:numberingXml.readNumberingXml,defaultValue:numberingXml.defaultNumbering}),readStylesFromZipFile=xmlFileReader({filename:"word/styles.xml",readElement:stylesReader.readStylesXml,defaultValue:stylesReader.defaultStyles})},{"../documents":5,
"../promises":24,"../results":25,"./body-reader":6,"./comments-reader":7,"./content-types-reader":8,"./document-xml-reader":9,"./files":1,"./notes-reader":11,"./numbering-xml":12,"./office-xml-reader":13,"./relationships-reader":14,"./styles-reader":16,path:193}],11:[function(require,module,exports){function createReader(noteType,bodyReader){function readNotesXml(element){return Result.combine(element.getElementsByTagName("w:"+noteType).filter(isFootnoteElement).map(readFootnoteElement))}function isFootnoteElement(element){var type=element.attributes["w:type"];return"continuationSeparator"!==type&&"separator"!==type}function readFootnoteElement(footnoteElement){var id=footnoteElement.attributes["w:id"];return bodyReader.readXmlElements(footnoteElement.children).map(function(body){return documents.Note({noteType:noteType,noteId:id,body:body})})}return readNotesXml}var documents=require("../documents"),Result=require("../results").Result;exports.createFootnotesReader=createReader.bind(this,"footnote"),exports.createEndnotesReader=createReader.bind(this,"endnote")},{"../documents":5,"../results":25}],12:[function(require,module,exports){function Numbering(nums){return{findLevel:function(numId,level){var num=nums[numId];return num?num[level]:null}}}function readNumberingXml(root){var abstractNums=readAbstractNums(root),nums=readNums(root,abstractNums);return new Numbering(nums)}function readAbstractNums(root){var abstractNums={};return root.getElementsByTagName("w:abstractNum").forEach(function(element){var id=element.attributes["w:abstractNumId"];abstractNums[id]=readAbstractNum(element)}),abstractNums}function readAbstractNum(element){var levels={};return element.getElementsByTagName("w:lvl").forEach(function(levelElement){var levelIndex=levelElement.attributes["w:ilvl"],numFmt=levelElement.first("w:numFmt").attributes["w:val"];levels[levelIndex]={isOrdered:"bullet"!==numFmt,level:levelIndex,format:numFmt}}),levels}function readNums(root,abstractNums){var nums={};return root.getElementsByTagName("w:num").forEach(function(element){var id=element.attributes["w:numId"],abstractNumId=element.first("w:abstractNumId").attributes["w:val"];nums[id]=abstractNums[abstractNumId]}),nums}exports.readNumberingXml=readNumberingXml,exports.Numbering=Numbering,exports.defaultNumbering=new Numbering({})},{}],13:[function(require,module,exports){function read(xmlString){return xml.readString(xmlString,xmlNamespaceMap).then(function(document){return collapseAlternateContent(document)[0]})}function readXmlFromZipFile(docxFile,path){return docxFile.exists(path)?docxFile.read(path,"utf-8").then(stripUtf8Bom).then(read):promises.resolve(null)}function stripUtf8Bom(xmlString){return xmlString.replace(/^\uFEFF/g,"")}function collapseAlternateContent(node){return"element"===node.type?"mc:AlternateContent"===node.name?node.first("mc:Fallback").children:(node.children=_.flatten(node.children.map(collapseAlternateContent,!0)),[node]):[node]}var _=require("underscore"),promises=require("../promises"),xml=require("../xml");exports.read=read,exports.readXmlFromZipFile=readXmlFromZipFile;var xmlNamespaceMap={"http://schemas.openxmlformats.org/wordprocessingml/2006/main":"w","http://schemas.openxmlformats.org/officeDocument/2006/relationships":"r","http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing":"wp","http://schemas.openxmlformats.org/drawingml/2006/main":"a","http://schemas.openxmlformats.org/drawingml/2006/picture":"pic","http://schemas.openxmlformats.org/package/2006/content-types":"content-types","urn:schemas-microsoft-com:vml":"v","http://schemas.openxmlformats.org/markup-compatibility/2006":"mc","urn:schemas-microsoft-com:office:word":"office-word"}},{"../promises":24,"../xml":32,underscore:215}],14:[function(require,module,exports){function readRelationships(element){var relationships={};return element.children.forEach(function(child){"{http://schemas.openxmlformats.org/package/2006/relationships}Relationship"===child.name&&(relationships[child.attributes.Id]={target:child.attributes.Target})}),relationships}exports.readRelationships=readRelationships},{}],15:[function(require,module,exports){function writeStyleMap(docxFile,styleMap){return docxFile.write(styleMapPath,styleMap),updateRelationships(docxFile).then(function(){return updateContentTypes(docxFile)})}function updateRelationships(docxFile){var path="word/_rels/document.xml.rels",relationshipsUri="http://schemas.openxmlformats.org/package/2006/relationships",relationshipElementName="{"+relationshipsUri+"}Relationship";return docxFile.read(path,"utf8").then(xml.readString).then(function(relationshipsContainer){var relationships=relationshipsContainer.children;addOrUpdateElement(relationships,relationshipElementName,"Id",{Id:"rMammothStyleMap",Type:schema,Target:styleMapAbsolutePath});var namespaces={"":relationshipsUri};return docxFile.write(path,xml.writeString(relationshipsContainer,namespaces))})}function updateContentTypes(docxFile){var path="[Content_Types].xml",contentTypesUri="http://schemas.openxmlformats.org/package/2006/content-types",overrideName="{"+contentTypesUri+"}Override";return docxFile.read(path,"utf8").then(xml.readString).then(function(typesElement){var children=typesElement.children;addOrUpdateElement(children,overrideName,"PartName",{PartName:styleMapAbsolutePath,ContentType:"text/prs.mammoth.style-map"});var namespaces={"":contentTypesUri};return docxFile.write(path,xml.writeString(typesElement,namespaces))})}function addOrUpdateElement(elements,name,identifyingAttribute,attributes){var existingElement=_.find(elements,function(element){return element.name===name&&element.attributes[identifyingAttribute]===attributes[identifyingAttribute]});existingElement?existingElement.attributes=attributes:elements.push(xml.element(name,attributes))}function readStyleMap(docxFile){return docxFile.exists(styleMapPath)?docxFile.read(styleMapPath,"utf8"):promises.resolve(null)}var _=require("underscore"),promises=require("../promises"),xml=require("../xml");exports.writeStyleMap=writeStyleMap,exports.readStyleMap=readStyleMap;var schema="http://schemas.zwobble.org/mammoth/style-map",styleMapPath="mammoth/style-map",styleMapAbsolutePath="/"+styleMapPath},{"../promises":24,"../xml":32,underscore:215}],16:[function(require,module,exports){function Styles(paragraphStyles,characterStyles){return{findParagraphStyleById:function(styleId){return paragraphStyles[styleId]},findCharacterStyleById:function(styleId){return characterStyles[styleId]}}}function readStylesXml(root){var paragraphStyles={},characterStyles={},styles={paragraph:paragraphStyles,character:characterStyles};return root.getElementsByTagName("w:style").forEach(function(styleElement){var style=readStyleElement(styleElement),styleSet=styles[style.type];styleSet&&(styleSet[style.styleId]=style)}),new Styles(paragraphStyles,characterStyles)}function readStyleElement(styleElement){var type=styleElement.attributes["w:type"],styleId=styleElement.attributes["w:styleId"],name=styleName(styleElement);return{type:type,styleId:styleId,name:name}}function styleName(styleElement){var nameElement=styleElement.first("w:name");return nameElement?nameElement.attributes["w:val"]:null}exports.readStylesXml=readStylesXml,exports.Styles=Styles,exports.defaultStyles=new Styles({},{})},{}],17:[function(require,module,exports){function topLevelElement(tagName,attributes){return elements([element(tagName,attributes,{fresh:!0})])}function elements(elementStyles){return new HtmlPath(elementStyles.map(function(elementStyle){return _.isString(elementStyle)?element(elementStyle):elementStyle}))}function HtmlPath(elements){this._elements=elements}function element(tagName,attributes,options){return options=options||{},new Element(tagName,attributes,options)}function Element(tagName,attributes,options){var tagNames={};_.isArray(tagName)?(tagName.forEach(function(tagName){tagNames[tagName]=!0}),tagName=tagName[0]):tagNames[tagName]=!0,this.tagName=tagName,this.tagNames=tagNames,this.attributes=attributes||{},this.fresh=options.fresh}var _=require("underscore"),html=require("./html");exports.topLevelElement=topLevelElement,exports.elements=elements,exports.element=element,HtmlPath.prototype.wrap=function(children){for(var result=children(),index=this._elements.length-1;index>=0;index--)result=this._elements[index].wrapNodes(result);return result},Element.prototype.matchesElement=function(element){return this.tagNames[element.tagName]&&_.isEqual(_.omit(this.attributes||{},"type"),_.omit(this.attributes||{},"type"))},Element.prototype.wrap=function(generateNodes){return this.wrapNodes(generateNodes())},Element.prototype.wrapNodes=function(nodes){return[html.elementWithTag(this,nodes)]},exports.empty=elements([]),exports.ignore={wrap:function(){return[]}}},{"./html":19,underscore:215}],18:[function(require,module,exports){function nonFreshElement(tagName,attributes,children){return elementWithTag(htmlPaths.element(tagName,attributes,{fresh:!1}),children)}function freshElement(tagName,attributes,children){return elementWithTag(htmlPaths.element(tagName,attributes,{fresh:!0}),children)}function elementWithTag(tag,children){return{type:"element",tag:tag,children:children||[]}}function selfClosingElement(tagName,attributes){return{type:"selfClosingElement",tagName:tagName,attributes:attributes}}function text(value){return{type:"text",value:value}}var htmlPaths=require("../html-paths"),forceWrite={type:"forceWrite"};exports.freshElement=freshElement,exports.nonFreshElement=nonFreshElement,exports.elementWithTag=elementWithTag,exports.selfClosingElement=selfClosingElement,exports.text=text,exports.forceWrite=forceWrite},{"../html-paths":17}],19:[function(require,module,exports){function write(writer,nodes){nodes.forEach(function(node){writeNode(writer,node)})}function writeNode(writer,node){toStrings[node.type](writer,node)}function generateElementString(writer,node){writer.open(node.tag.tagName,node.tag.attributes),write(writer,node.children),writer.close(node.tag.tagName)}function generateSelfClosingElementString(writer,node){writer.selfClosing(node.tagName,node.attributes)}function generateTextString(writer,node){writer.text(node.value)}var ast=require("./ast");exports.freshElement=ast.freshElement,exports.nonFreshElement=ast.nonFreshElement,exports.elementWithTag=ast.elementWithTag,exports.selfClosingElement=ast.selfClosingElement,exports.text=ast.text,exports.forceWrite=ast.forceWrite,exports.simplify=require("./simplify");var toStrings={element:generateElementString,selfClosingElement:generateSelfClosingElementString,text:generateTextString,forceWrite:function(){}};exports.write=write},{"./ast":18,"./simplify":20}],20:[function(require,module,exports){function simplify(nodes){return collapse(removeEmpty(nodes))}function collapse(nodes){var children=[];return nodes.map(collapseNode).forEach(function(child){appendChild(children,child)}),children}function collapseNode(node){return collapsers[node.type](node)}function collapseElement(node){return ast.elementWithTag(node.tag,collapse(node.children))}function identity(value){return value}function appendChild(children,child){var lastChild=children[children.length-1];"element"===child.type&&!child.tag.fresh&&lastChild&&"element"===lastChild.type&&child.tag.matchesElement(lastChild.tag)?child.children.forEach(function(grandChild){appendChild(lastChild.children,grandChild)}):children.push(child)}function removeEmpty(nodes){return flatMap(nodes,function(node){return emptiers[node.type](node)})}function flatMap(values,func){return _.flatten(_.map(values,func),!0)}function neverEmpty(node){return[node]}function elementEmptier(element){var children=removeEmpty(element.children);return 0===children.length?[]:ast.elementWithTag(element.tag,children)}function textEmptier(node){return 0===node.value.length?[]:[node]}var _=require("underscore"),ast=require("./ast"),collapsers={element:collapseElement,selfClosingElement:identity,text:identity,forceWrite:identity},emptiers={element:elementEmptier,selfClosingElement:neverEmpty,text:textEmptier,forceWrite:neverEmpty};module.exports=simplify},{"./ast":18,underscore:215}],21:[function(require,module,exports){var _=require("underscore"),promises=require("./promises"),Html=require("./html");exports.imgElement=function(func){return function(element,messages){return promises.when(func(element)).then(function(result){var attributes=_.clone(result);return element.altText&&(attributes.alt=element.altText),[Html.selfClosingElement("img",attributes)]})}},exports.inline=exports.imgElement},{"./html":19,"./promises":24,underscore:215}],22:[function(require,module,exports){function convertToHtml(input,options){return convert(input,options)}function convertToMarkdown(input,options){var markdownOptions=Object.create(options||{});return markdownOptions.outputFormat="markdown",convert(input,markdownOptions)}function convert(input,options){return options=Object.create(options||{}),unzip.openZip(input).tap(function(docxFile){return options.styleMap?void 0:docxStyleMap.readStyleMap(docxFile).then(function(styleMap){options.styleMap=styleMap||""})}).then(function(docxFile){var fullOptions=readOptions(options);return docxReader.read(docxFile,input).then(function(documentResult){return documentResult.map(fullOptions.transformDocument)}).then(function(documentResult){return convertDocumentToHtml(documentResult,fullOptions)})})}function readEmbeddedStyleMap(input){return unzip.openZip(input).then(docxStyleMap.readStyleMap)}function convertDocumentToHtml(documentResult,options){var parsedOptions=Object.create(options),styleMapResult=parseStyleMap(options.styleMap);parsedOptions.styleMap=styleMapResult.value;var documentConverter=new DocumentConverter(parsedOptions);return documentResult.flatMapThen(function(document){return styleMapResult.flatMapThen(function(styleMap){return documentConverter.convertToHtml(document)})})}function parseStyleMap(styleMap){return Result.combine((styleMap||[]).map(readStyle)).map(function(styleMap){return styleMap.filter(function(styleMapping){return!!styleMapping})})}function extractRawText(input){return unzip.openZip(input).then(docxReader.read).then(function(documentResult){return documentResult.map(convertElementToRawText)})}function convertElementToRawText(element){if("text"===element.type)return element.value;var tail="paragraph"===element.type?"\n\n":"";return(element.children||[]).map(convertElementToRawText).join("")+tail}function embedStyleMap(input,styleMap){return unzip.openZip(input).tap(function(docxFile){return docxStyleMap.writeStyleMap(docxFile,styleMap)}).then(function(docxFile){return{toBuffer:docxFile.toBuffer}})}var docxReader=(require("underscore"),require("./docx/docx-reader")),docxStyleMap=require("./docx/style-map"),DocumentConverter=require("./document-to-html").DocumentConverter,readStyle=require("./style-reader").readStyle,readOptions=require("./options-reader").readOptions,unzip=require("./unzip"),Result=require("./results").Result;exports.convertToHtml=convertToHtml,exports.convertToMarkdown=convertToMarkdown,exports.convert=convert,exports.extractRawText=extractRawText,exports.images=require("./images"),exports.transforms=require("./transforms"),exports.underline=require("./underline"),exports.embedStyleMap=embedStyleMap,exports.readEmbeddedStyleMap=readEmbeddedStyleMap,exports.styleMapping=function(){throw new Error("Use a raw string instead of mammoth.styleMapping e.g. \"p[style-name='Title'] => h1\" instead of mammoth.styleMapping(\"p[style-name='Title'] => h1\")")}},{"./document-to-html":4,"./docx/docx-reader":10,"./docx/style-map":15,"./images":21,"./options-reader":23,"./results":25,"./style-reader":26,"./transforms":27,"./underline":28,"./unzip":2,underscore:215}],23:[function(require,module,exports){function readOptions(options){options=options||{};var fullOptions={};return _.extend(fullOptions,standardOptions,options),fullOptions.styleMap=readStyleMap(options.styleMap,fullOptions),fullOptions}function readStyleMap(styleMap,options){var customStyleMap=readCustomStyleMap(styleMap);return customStyleMap.concat(options.includeDefaultStyleMap?standardOptions.styleMap:[])}function readCustomStyleMap(styleMap){return styleMap?_.isString(styleMap)?styleMap.split("\n").filter(function(line){return"#"!==line.charAt(0)}).map(function(line){return line.trim()}):styleMap:[]}function identity(value){return value}exports.readOptions=readOptions;var _=require("underscore"),standardOptions=exports._standardOptions={styleMap:["p.Heading1 => h1:fresh","p.Heading2 => h2:fresh","p.Heading3 => h3:fresh","p.Heading4 => h4:fresh","p[style-name='Heading 1'] => h1:fresh","p[style-name='Heading 2'] => h2:fresh","p[style-name='Heading 3'] => h3:fresh","p[style-name='Heading 4'] => h4:fresh","p[style-name='heading 1'] => h1:fresh","p[style-name='heading 2'] => h2:fresh","p[style-name='heading 3'] => h3:fresh","p[style-name='heading 4'] => h4:fresh","p[style-name='heading 4'] => h4:fresh","r[style-name='Strong'] => strong","p[style-name='footnote text'] => p","r[style-name='footnote reference'] =>","p[style-name='endnote text'] => p","r[style-name='endnote reference'] =>","p[style-name='annotation text'] => p","r[style-name='annotation reference'] =>","p[style-name='Footnote'] => p","r[style-name='Footnote anchor'] =>","p[style-name='Endnote'] => p","r[style-name='Endnote anchor'] =>","p:unordered-list(1) => ul > li:fresh","p:unordered-list(2) => ul|ol > li > ul > li:fresh","p:unordered-list(3) => ul|ol > li > ul|ol > li > ul > li:fresh","p:unordered-list(4) => ul|ol > li > ul|ol > li > ul|ol > li > ul > li:fresh","p:unordered-list(5) => ul|ol > li > ul|ol > li > ul|ol > li > ul|ol > li > ul > li:fresh","p:ordered-list(1) => ol > li:fresh","p:ordered-list(2) => ul|ol > li > ol > li:fresh","p:ordered-list(3) => ul|ol > li > ul|ol > li > ol > li:fresh","p:ordered-list(4) => ul|ol > li > ul|ol > li > ul|ol > li > ol > li:fresh","p:ordered-list(5) => ul|ol > li > ul|ol > li