-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
116 lines (101 loc) · 2.83 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import sax from "sax";
const TYPED_ATTRS = [
"id",
"uid",
"changeset",
"visible",
"version",
"lon",
"lat",
"ref",
"min_lon",
"min_lat",
"max_lon",
"max_lat",
"comments_count",
"changes_count",
"open",
];
function parseAttributes(attributes) {
for (let attr of TYPED_ATTRS) {
if (attributes[attr] !== undefined) {
try {
attributes[attr] = JSON.parse(attributes[attr]);
} catch {
throw new Error(
`Failed to parse value "${attributes[attr]}" for attribute "${attr}" (expected a JSON value)`,
);
}
}
}
return attributes;
}
function parseAugmentedDiff(xmlData) {
return new Promise((resolve, reject) => {
var xmlParser = sax.parser(true /* strict mode */, { lowercase: true });
var currentXmlTag = null;
var currentAction = {};
var currentElement = {};
var currentMember = {};
var result = { actions: [] };
xmlParser.onopentag = function (node) {
var symbol = node.name;
currentXmlTag = symbol;
if (symbol === "meta") {
result.meta = { ...result.meta, ...node.attributes };
return;
}
var attrs = parseAttributes(node.attributes);
if (symbol === "action") {
currentAction = { type: attrs.type };
}
if (symbol === "node" || symbol === "way" || symbol === "relation") {
currentElement = { type: symbol, ...attrs, tags: {} };
if (symbol === "way") {
currentElement.nodes = [];
}
if (symbol === "relation") {
currentElement.members = [];
currentMember = {};
}
}
if (symbol === "tag" && currentElement) {
currentElement.tags[attrs.k] = attrs.v;
}
if (symbol === "nd" && currentElement && currentElement.type === "way") {
currentElement.nodes.push(attrs);
}
if (symbol === "nd" && currentElement && currentElement.type === "relation") {
currentMember.nodes.push(attrs);
}
if (symbol === "member" && currentElement && currentElement.type === "relation") {
currentMember = { ...attrs, nodes: [] };
currentElement.members.push(currentMember);
}
};
xmlParser.ontext = function (text) {
if (currentXmlTag === "note") {
result.note = text;
}
};
xmlParser.onclosetag = function (symbol) {
if (symbol === "old" || symbol === "new") {
currentAction[symbol] = currentElement;
}
if (symbol === "action") {
if (currentAction.type == "create") {
currentAction.new = currentElement;
}
result.actions.push(currentAction);
}
if (symbol === "osm") {
resolve(result);
}
currentXmlTag = null;
};
xmlParser.onerror = reject;
xmlParser.write(xmlData);
xmlParser.close();
});
}
export default parseAugmentedDiff;