UNPKG

6.16 kBJavaScriptView Raw
1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT License. See License.txt in the project root for license information.
3var _a, _b;
4var parser = new DOMParser();
5// Policy to make our code Trusted Types compliant.
6// https://github.com/w3c/webappsec-trusted-types
7// We are calling DOMParser.parseFromString() to parse XML payload from Azure services.
8// The parsed DOM object is not exposed to outside. Scripts are disabled when parsing
9// according to the spec. There are no HTML/XSS security concerns on the usage of
10// parseFromString() here.
11var ttPolicy;
12try {
13 if (typeof self.trustedTypes !== "undefined") {
14 ttPolicy = self.trustedTypes.createPolicy("@azure/ms-rest-js#xml.browser", {
15 createHTML: function (s) { return s; },
16 });
17 }
18}
19catch (e) {
20 console.warn('Could not create trusted types policy "@azure/ms-rest-js#xml.browser"');
21}
22export function parseXML(str) {
23 var _a;
24 try {
25 var dom = parser.parseFromString(((_a = ttPolicy === null || ttPolicy === void 0 ? void 0 : ttPolicy.createHTML(str)) !== null && _a !== void 0 ? _a : str), "application/xml");
26 throwIfError(dom);
27 var obj = domToObject(dom.childNodes[0]);
28 return Promise.resolve(obj);
29 }
30 catch (err) {
31 return Promise.reject(err);
32 }
33}
34var errorNS = "";
35try {
36 var invalidXML = ((_a = ttPolicy === null || ttPolicy === void 0 ? void 0 : ttPolicy.createHTML("INVALID")) !== null && _a !== void 0 ? _a : "INVALID");
37 errorNS = (_b = parser.parseFromString(invalidXML, "text/xml").getElementsByTagName("parsererror")[0]
38 .namespaceURI) !== null && _b !== void 0 ? _b : "";
39}
40catch (ignored) {
41 // Most browsers will return a document containing <parsererror>, but IE will throw.
42}
43function throwIfError(dom) {
44 if (errorNS) {
45 var parserErrors = dom.getElementsByTagNameNS(errorNS, "parsererror");
46 if (parserErrors.length) {
47 throw new Error(parserErrors.item(0).innerHTML);
48 }
49 }
50}
51function isElement(node) {
52 return !!node.attributes;
53}
54/**
55 * Get the Element-typed version of the provided Node if the provided node is an element with
56 * attributes. If it isn't, then undefined is returned.
57 */
58function asElementWithAttributes(node) {
59 return isElement(node) && node.hasAttributes() ? node : undefined;
60}
61function domToObject(node) {
62 var result = {};
63 var childNodeCount = node.childNodes.length;
64 var firstChildNode = node.childNodes[0];
65 var onlyChildTextValue = (firstChildNode &&
66 childNodeCount === 1 &&
67 firstChildNode.nodeType === Node.TEXT_NODE &&
68 firstChildNode.nodeValue) ||
69 undefined;
70 var elementWithAttributes = asElementWithAttributes(node);
71 if (elementWithAttributes) {
72 result["$"] = {};
73 for (var i = 0; i < elementWithAttributes.attributes.length; i++) {
74 var attr = elementWithAttributes.attributes[i];
75 result["$"][attr.nodeName] = attr.nodeValue;
76 }
77 if (onlyChildTextValue) {
78 result["_"] = onlyChildTextValue;
79 }
80 }
81 else if (childNodeCount === 0) {
82 result = "";
83 }
84 else if (onlyChildTextValue) {
85 result = onlyChildTextValue;
86 }
87 if (!onlyChildTextValue) {
88 for (var i = 0; i < childNodeCount; i++) {
89 var child = node.childNodes[i];
90 // Ignore leading/trailing whitespace nodes
91 if (child.nodeType !== Node.TEXT_NODE) {
92 var childObject = domToObject(child);
93 if (!result[child.nodeName]) {
94 result[child.nodeName] = childObject;
95 }
96 else if (Array.isArray(result[child.nodeName])) {
97 result[child.nodeName].push(childObject);
98 }
99 else {
100 result[child.nodeName] = [result[child.nodeName], childObject];
101 }
102 }
103 }
104 }
105 return result;
106}
107// tslint:disable-next-line:no-null-keyword
108var doc = document.implementation.createDocument(null, null, null);
109var serializer = new XMLSerializer();
110export function stringifyXML(obj, opts) {
111 var rootName = (opts && opts.rootName) || "root";
112 var dom = buildNode(obj, rootName)[0];
113 return ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' + serializer.serializeToString(dom));
114}
115function buildAttributes(attrs) {
116 var result = [];
117 for (var _i = 0, _a = Object.keys(attrs); _i < _a.length; _i++) {
118 var key = _a[_i];
119 var attr = doc.createAttribute(key);
120 attr.value = attrs[key].toString();
121 result.push(attr);
122 }
123 return result;
124}
125function buildNode(obj, elementName) {
126 if (typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean") {
127 var elem = doc.createElement(elementName);
128 elem.textContent = obj.toString();
129 return [elem];
130 }
131 else if (Array.isArray(obj)) {
132 var result = [];
133 for (var _i = 0, obj_1 = obj; _i < obj_1.length; _i++) {
134 var arrayElem = obj_1[_i];
135 for (var _a = 0, _b = buildNode(arrayElem, elementName); _a < _b.length; _a++) {
136 var child = _b[_a];
137 result.push(child);
138 }
139 }
140 return result;
141 }
142 else if (typeof obj === "object") {
143 var elem = doc.createElement(elementName);
144 for (var _c = 0, _d = Object.keys(obj); _c < _d.length; _c++) {
145 var key = _d[_c];
146 if (key === "$") {
147 for (var _e = 0, _f = buildAttributes(obj[key]); _e < _f.length; _e++) {
148 var attr = _f[_e];
149 elem.attributes.setNamedItem(attr);
150 }
151 }
152 else {
153 for (var _g = 0, _h = buildNode(obj[key], key); _g < _h.length; _g++) {
154 var child = _h[_g];
155 elem.appendChild(child);
156 }
157 }
158 }
159 return [elem];
160 }
161 else {
162 throw new Error("Illegal value passed to buildObject: " + obj);
163 }
164}
165//# sourceMappingURL=xml.browser.js.map
\No newline at end of file