/** * Translates a text string from one language to another. * @method getTranslationAsync * @param {string} text * Required. A string representing the text to translate. The size of the text must not exceed 10000 characters. * @param {string} from * Optional. A string representing the language code of the translation text. For example, en for English. * @param {string} to * Optional. A string representing the language code to translate the text into. * @returns {string} * A string representing the translated text. */ public async getTranslationAsync(text: string, from?: string, to: string = "en"): Promise<string | undefined> { let translatorApiKey = process.env.COGNITIVE_TRANSLATOR_API_KEY; if (!translatorApiKey) { throw new Error('translator text api key is undefined') } if (!text) { throw new Error('text argument is empty or undefined') } let encodedText = encodeURIComponent(text); let url = `${baseUrl}/Translate?text=${encodedText}`; if (from) { url += `&from=${from}`; } if (to) { url += `&to=${to}` } let response = await fetch(url, { method: 'GET', headers: { 'Ocp-Apim-Subscription-Key': translatorApiKey, } }) .catch(error => console.error(error)); if (response && response.status && response.status >= 200 && response.status <= 299) { let xmlcontent = await response.text() if (xmlcontent) { let json = xmljs.xml2js(xmlcontent, { compact: true, ignoreAttributes: true }); if (json && json.string && json.string._text) { return json.string._text; } } } return undefined; }
private extractDocumentRefs(xmlData: string): IDocumentRefs { const xmlObj = xml2js(xmlData, { compact: true }) as XMLElementCompact; const sectionProp = xmlObj["w:document"]["w:body"]["w:sectPr"]; const headerProps: XMLElementCompact = sectionProp["w:headerReference"]; let headersXmlArray: XMLElementCompact[]; if (headerProps === undefined) { headersXmlArray = []; } else if (Array.isArray(headerProps)) { headersXmlArray = headerProps; } else { headersXmlArray = [headerProps]; } const headers = headersXmlArray.map((item) => { if (item._attributes === undefined) { throw Error("header referecne element has no attributes"); } return { type: item._attributes["w:type"] as HeaderReferenceType, id: this.parseRefId(item._attributes["r:id"] as string), }; }); const footerProps: XMLElementCompact = sectionProp["w:footerReference"]; let footersXmlArray: XMLElementCompact[]; if (footerProps === undefined) { footersXmlArray = []; } else if (Array.isArray(footerProps)) { footersXmlArray = footerProps; } else { footersXmlArray = [footerProps]; } const footers = footersXmlArray.map((item) => { if (item._attributes === undefined) { throw Error("footer referecne element has no attributes"); } return { type: item._attributes["w:type"] as FooterReferenceType, id: this.parseRefId(item._attributes["r:id"] as string), }; }); return { headers, footers }; }
/** * Retrieves friendly names for the languages passed in as the parameter languageCode, * and localized using the passed locale language. * @method getLanguageNameAsync * @param {string} languageCode * Required. A string representing the ISO 639-1 language code to retrieve the friendly names for. * @param {string} locale * Optional. A string representing a combination of an ISO 639 two-letter lowercase culture code * associated with a language and an ISO 3166 two-letter uppercase subculture code to localize the language names or a ISO 639 lowercase culture code by itself. * @returns {string} * A string representing the translated text. */ public async getLanguageNameAsync(languageCode: string, locale: string = "en"): Promise<string | undefined> { let code = encodeURIComponent(languageCode); let translatorApiKey = process.env.COGNITIVE_TRANSLATOR_API_KEY; // Check if environment variables are correct if (translatorApiKey == undefined) { console.log("Cognitive Services - Translation - Url or Api Key undefined."); return undefined; } let query = `${baseUrl}/GetLanguageNames?locale=${locale}`; let response = await fetch(query, { method: 'POST', headers: { 'Ocp-Apim-Subscription-Key': translatorApiKey, 'Content-Type': 'text/xml' }, body: `<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays"> <string>${languageCode}</string> </ArrayOfstring>` }) .catch(error => console.error(error)); if (response && response.status && response.status >= 200 && response.status <= 299) { let xmlcontent = await response.text() if (xmlcontent) { let json = xmljs.xml2js(xmlcontent, { compact: true, ignoreAttributes: true }); if (json && json.ArrayOfstring && json.ArrayOfstring.string && json.ArrayOfstring.string._text) { return json.ArrayOfstring.string._text; } } } return undefined; }
private findReferenceFiles(xmlData: string): IRelationshipFileInfo[] { const xmlObj = xml2js(xmlData, { compact: true }) as XMLElementCompact; const relationXmlArray = Array.isArray(xmlObj.Relationships.Relationship) ? xmlObj.Relationships.Relationship : [xmlObj.Relationships.Relationship]; const relationships: IRelationshipFileInfo[] = relationXmlArray .map((item: XMLElementCompact) => { if (item._attributes === undefined) { throw Error("relationship element has no attributes"); } return { id: this.parseRefId(item._attributes.Id as string), type: schemeToType[item._attributes.Type as string], target: item._attributes.Target as string, }; }) .filter((item) => item.type !== null); return relationships; }
/** * Creates new Style based on the given styles. * Parses the styles and convert them to XmlComponent. * Example content from styles.xml: * <?xml version="1.0"> * <w:styles xmlns:mc="some schema" ...> * * <w:style w:type="paragraph" w:styleId="Heading1"> * <w:name w:val="heading 1"/> * ..... * </w:style> * * <w:style w:type="paragraph" w:styleId="Heading2"> * <w:name w:val="heading 2"/> * ..... * </w:style> * * <w:docDefaults>Or any other element will be parsed to</w:docDefaults> * * </w:styles> * @param externalStyles context from styles.xml */ public newInstance(xmlData: string): Styles { const xmlObj = xml2js(xmlData, { compact: false }) as XMLElement; let stylesXmlElement: XMLElement | undefined; for (const xmlElm of xmlObj.elements || []) { if (xmlElm.name === "w:styles") { stylesXmlElement = xmlElm; } } if (stylesXmlElement === undefined) { throw new Error("can not find styles element"); } const importedStyle = new Styles(new ImportedRootElementAttributes(stylesXmlElement.attributes)); const stylesElements = stylesXmlElement.elements || []; for (const childElm of stylesElements) { importedStyle.push(convertToXmlComponent(childElm) as ImportedXmlComponent); } return importedStyle; }
.map(async (reference, i) => { const relationshipFileInfo = documentRelationships.find((rel) => rel.id === reference.id); if (relationshipFileInfo === null || !relationshipFileInfo) { throw new Error(`Can not find target file for id ${reference.id}`); } const xmlData = await zipContent.files[`word/${relationshipFileInfo.target}`].async("text"); const xmlObj = xml2js(xmlData, { compact: false, captureSpacesBetweenElements: true }) as XMLElement; if (!xmlObj.elements) { return undefined; } const xmlElement = xmlObj.elements.reduce((acc, current) => (current.name === "w:ftr" ? current : acc)); const importedComp = convertToXmlComponent(xmlElement) as ImportedXmlComponent; const wrapper = new FooterWrapper(media, startingRelationshipId + i, importedComp); await this.addRelationshipToWrapper(relationshipFileInfo, zipContent, wrapper, media); return { type: reference.type, footer: wrapper }; })
private checkIfTitlePageIsDefined(xmlData: string): boolean { const xmlObj = xml2js(xmlData, { compact: true }) as XMLElementCompact; const sectionProp = xmlObj["w:document"]["w:body"]["w:sectPr"]; return sectionProp["w:titlePg"] !== undefined; }
/** * Converts the xml string to a XmlComponent tree. * * @param importedContent xml content of the imported component */ public static fromXmlString(importedContent: string): ImportedXmlComponent { const xmlObj = xml2js(importedContent, { compact: false }) as XmlElement; return convertToXmlComponent(xmlObj) as ImportedXmlComponent; }
it("should convert to xml component", () => { const xmlObj = xml2js(xmlString, { compact: false }) as Element; const converted = convertToXmlComponent(xmlObj); expect(converted).to.deep.equal(convertedXmlElement); });
export const xmlToTreeNode = memoize((xml: string): TreeNode => { return normalizeTree(xml2js(xml).elements[0]); });