Repository navigation
Expand file tree
/
Copy pathExtractor.js
More file actions
694 lines (637 loc) · 20.9 KB
/
Copy pathExtractor.js
File metadata and controls
694 lines (637 loc) · 20.9 KB
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
/**
* Default metadata extractor.
*/
// TODO inherited xpath issue: we need more test cases to actually address this
// TODO more field ops: predicates, parallels, pattern matchers, etc
/**
* A convenient class for creating scopes. A scope is essentially an Object.
* @constructor
* @param {string} id
* The ID of this scope.
* @param {Scope} parent
* The parent scope.
*/
function Scope(id, parent) {
this._id = (parent ? (parent._id + '.') : '') + id;
if (parent instanceof Scope) {
this._parent = parent;
parent.subscopes = parent.subscopes || [];
parent.subscopes.push(this);
}
}
/**
* Trace a value in this scope and its ancestors for a given key.
* @param {string} key
* The key to the value to be traced.
* @param {string} component
* The name of the component to trace in this scope and its ancestors. Each
* scope can have multiple components.
* @return {Object} The first value with the given key (and in the component, if
* specified) in this scope or in its ancestors.
*/
Scope.prototype.trace = function(key, component) {
var obj = this;
while (obj) {
var comp = component ? obj[component] : obj;
if (comp && key in comp) {
return comp[key];
}
obj = obj._parent;
}
return null;
}
/**
* An extraction task.
* @constructor
* @param {Response} resp
* Must contain 'entity' as root DOM element.
* @param {MetaMetadata} mmd
* The meta-metadata used for extraction.
* @param {BigSemantics} bsFacade
* BigSemantics facade. Nullable.
* @param {Object} options
* Additional options. Nullable.
*/
function Extraction(resp, mmd, bsFacade, options) {
if (resp === undefined || resp === null) {
throw new Error("Required argument missing: resp");
}
if (resp.entity === undefined || resp.entity === null) {
throw new Error("Required argument missing: resp.entity");
}
if (mmd === undefined || mmd === null) {
throw new Error("Required argument missing: mmd");
}
this.response = resp;
this.location = new ParsedURL(this.response.location);
this.rootNode = resp.entity;
this.rawMmd = mmd;
this.mmd = BSUtils.unwrapMmd(mmd);
this.bs = bsFacade;
this.options = options || {};
return this;
}
Extraction.prototype.isScalar = function(field) {
return field.scalar ? true : false;;
}
Extraction.prototype.isScalarCollection = function(field) {
return (field.collection && field.collection.child_scalar_type) ? true : false;
}
Extraction.prototype.isComposite = function(field) {
return field.composite ? true : false;
}
Extraction.prototype.isCompositeCollection = function(field) {
return (field.collection && field.collection.child_type) ? true : false;
}
/**
* Find the context node for a given field and its parent scope.
* @param {MetaMetadataField} field
* The mmd field potentially specifying context node.
* @param {Scope} parentScope
* The parent scope of the field.
* @return {Node} The context node.
*/
Extraction.prototype.getContextNode = function(field, parentScope) {
var result = null;
if (field.context_node) {
result = parentScope.trace(field.context_node, 'vars');
}
else {
result = parentScope.node;
}
if (result === null) {
console.error("Context node is null: something is definitely wrong!");
}
return result;
}
/**
* Handles def_vars defined inside a field, using its local scope.
* @param {MetaMetadataField} field
* The mmd field containing def_vars.
* @param {Scope} localScope
* The extraction scope for this field.
* @return {Object} An object containing def var names and values.
*/
Extraction.prototype.handleDefVars = function(field, localScope) {
var result = {};
if (field.def_vars instanceof Array) {
for (var i = 0; i < field.def_vars.length; ++i) {
var defVar = field.def_vars[i];
if (defVar.type === 'node') {
if (defVar.name && defVar.xpaths instanceof Array) {
for (var j = 0; j < defVar.xpaths.length; ++j) {
var xpath = defVar.xpaths[j];
var targetNode = this.evaluateFirstNode(xpath, localScope.contextNode);
if (targetNode) {
result[defVar.name] = targetNode.singleNodeValue;
break;
}
}
}
}
else {
console.warn("Unknown def_var type: %O", defVar);
}
}
}
return Object.keys(result).length > 0 ? result : null;
}
/**
* Amends an XPath. This mainly includes joining multiple lines if any, turning
* absolute XPaths to relative ones, and resolving metadata-related variables in
* the XPath.
* @param {string} xpath
* The XPath to amend.
* @param {Scope} parentScope
* The parent scope of the field that has the XPath. Used to resolve
* metadata-related variables.
* @return {string} Amended XPath.
*/
Extraction.prototype.amendXpath = function(xpath, parentScope) {
var result = xpath;
if (typeof result === 'string') {
// join multiple lines
result = result.replace('\n', '').replace('\r', '');
// absolute to relative
// FIXME use a real xpath parser, e.g. https://github.com/dodo/xpath-parser
if (result.indexOf('/') === 0) {
result = '.' + result;
}
if (result.indexOf('(/') === 0) {
result = result.replace('(/', '(./');
}
// replace $i to index in the parent which must be collection
if (parentScope && parentScope.collectionIndex && result.indexOf('$i') >= 0) {
result = result.replace('$i', parentScope.collectionIndex);
}
}
return result;
}
Extraction.prototype.evaluateFirstNode = function(xpath, contextNode, parentScope) {
xpath = this.amendXpath(xpath, parentScope);
return this.rootNode.evaluate(xpath, contextNode, null, XPathResult.FIRST_ORDERED_NODE_TYPE);
}
Extraction.prototype.evaluateAllNodes = function(xpath, contextNode, parentScope) {
xpath = this.amendXpath(xpath, parentScope);
return this.rootNode.evaluate(xpath, contextNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE);
}
/**
* Turns a scalar value represented in raw string to a typed value.
* @param {string} val
* The scalar value in a raw string.
* @param {string} scalarType
* The scalar type.
* @return {any} The converted, typed value.
*/
Extraction.prototype.toTypedScalar = function(val, scalarType) {
if (val && scalarType) {
switch (scalarType) {
case 'String':
break;
case 'Int':
case 'Integer':
case 'Float':
case 'Double':
case 'Number':
val = Number(val);
break;
case 'Bool':
case 'Boolean':
val = Boolean(val);
break;
case 'URL':
case 'ParsedURL':
var purl = new ParsedURL(val, this.location.base);
// FIXME filter purl asynchronously
val = purl.toString();
break;
default:
console.warn("Scalar type unsupported yet: " + scalarType + "; for value: " + val);
}
}
return val;
}
Extraction.prototype.extractScalar = function(field, parentScope) {
// step 1: prepare objects used in extraction
var contextNode = this.getContextNode(field, parentScope);
var value = null;
// step 2: do extraction
// TODO case 2.1: extract from previous field op result
// case 2.2: regular xpath extraction
if (!value && contextNode && field.xpaths instanceof Array) {
for (var i = 0; i < field.xpaths.length; ++i) {
var xpath = field.xpaths[i];
var xres = this.evaluateFirstNode(xpath, contextNode, parentScope);
if (xres && xres.singleNodeValue && xres.singleNodeValue.textContent) {
if (field.extract_as_html) {
value = xres.singleNodeValue.innerHTML;
} else {
value = xres.singleNodeValue.textContent.trim();
}
break;
}
}
}
// step 3: apply field ops
if (field.field_ops) {
value = FieldOps.operate(value, field.field_ops);
}
if (field.concatenate_values) {
FieldOps.concatenateValues(field.concatenate_values, parentScope);
}
value = this.toTypedScalar(value, field.scalar_type);
return value;
}
Extraction.prototype.extractScalarCollection = function(field, parentScope) {
// step 1: prepare objects used in extraction
var contextNode = this.getContextNode(field, parentScope);
var value = null;
// step 2: do extraction
// TODO case 2.1: extract from previous field op result
// case 2.2: regular xpath extraction
if (!value && contextNode && field.xpaths instanceof Array) {
for (var i = 0; i < field.xpaths.length; ++i) {
var xpath = field.xpaths[i];
var xres = this.evaluateAllNodes(xpath, contextNode, parentScope);
if (xres && xres.snapshotLength > 0) {
value = [];
for (var j = 0; j < xres.snapshotLength; ++j) {
var item = xres.snapshotItem(j).textContent;
if (item) {
value.push(item.trim());
}
}
break;
}
}
}
// TODO step 3: apply field ops
if (value && value.length > 0) {
var typed = [];
for (var i in value) {
typed.push(this.toTypedScalar(value[i], field.child_scalar_type));
}
return typed;
}
return null;
}
/**
* If srcField is inheriting from targetField.
* @param {MetaMetadataField} srcField
* @param {MetaMetadataField} targetField
* @return {Boolean}
*/
Extraction.prototype.isFieldInheritingFrom = function(srcField, targetField) {
if (srcField) {
var f = targetField;
while (f) {
f = this.unwrapField(f);
if (srcField.name !== f.name) return false;
if (srcField === f) return true;
f = f.super_field;
}
}
return false;
}
/**
* If we will result in infinite recursion with the input scope (which
* represents a stage of the extraction process).
* @param {Scope} scope
* The current scope.
* @return {Boolean}
*/
Extraction.prototype.isInfiniteRecursion = function(scope) {
if (scope) {
var field = scope.field;
var contextNode = scope.contextNode;
if (field && contextNode) {
var ancestor = scope._parent;
while (ancestor) {
var inheriting = this.isFieldInheritingFrom(field, ancestor.field);
var inherited = this.isFieldInheritingFrom(ancestor.field, field);
if ((inheriting || inherited) && ancestor.contextNode === contextNode) {
return true;
}
ancestor = ancestor._parent;
}
return false;
}
}
return true;
}
Extraction.prototype.extractComposite = function(field, parentScope) {
// step 1: prepare local scope for extracting nested fields
var localScope = new Scope(field.name, parentScope);
localScope.field = field;
localScope.contextNode = this.getContextNode(field, parentScope);
localScope.vars = this.handleDefVars(field, localScope);
localScope.value = null;
var done = false; // true iff localScope is ready for extraction
// detect and prevent infinite recursion
if (this.isInfiniteRecursion(localScope)) {
return null;
}
// case 1.1: extract root metadata as composite
if (parentScope.rootNode) {
localScope.value = {
location: this.response.location,
additional_locations: this.response.otherLocations,
};
localScope.node = parentScope.rootNode;
}
// TODO case 1.2: extract from previous field op result (and set done)
// case 1.3: regular xpath extraction
if (!done && localScope.contextNode) {
var xpaths = field.xpaths || [];
/* FIXME this solution to the inherited xpath issue doesn't work for all
* cases. we need to have more test cases to address it.
var superFieldXpaths = this.unwrapField(field.super_field || {}).xpaths || [];
if (!parentScope.rootNode && xpaths.length === superFieldXpaths.length) {
localScope.node = localScope.contextNode;
localScope.authoredKidsOnly = true;
localScope.value = localScope.value || {};
done = true;
}
else {
*/
for (var i = 0; i < xpaths.length; ++i) {
var xpath = xpaths[i];
var xres = this.evaluateFirstNode(xpath, localScope.contextNode, parentScope);
if (xres && xres.singleNodeValue) {
localScope.node = xres.singleNodeValue;
localScope.value = localScope.value || {};
done = true;
break;
}
}
/* FIXME (solution to the inherited xpath issue)
}
*/
}
// step 2: extract nested fields using the newly created local scope
if (localScope.value) {
localScope.value.meta_metadata_name = field.type || field.name;
var kids = field.kids || [];
/* FIXME (solution to the inherited xpath issue)
// if we only allow authored kids to be extracted, filter `kids`.
if (localScope.authoredKidsOnly) {
if (!field._authored_kids) {
field._authored_kids = [];
var superkids = this.unwrapField(field.super_field || {}).kids || [];
for (var i = 0; i < field.kids.length; ++i) {
var kid = kids[i];
var found = false;
for (var j = 0; j < superkids.length; ++j) {
var superkid = superkids[j];
if (this.unwrapField(kid) === this.unwrapField(superkid)) {
found = true;
break;
}
}
if (!found) field._authored_kids.push(kid);
}
}
kids = field._authored_kids;
}
*/
this.extractFields(kids, localScope, localScope.value);
if (Object.keys(localScope.value).length > 1) {
if (field.polymorphic_scope || field.polymorphic_classes) {
// TODO change meta_metadata_name based on location
var wrapper = {};
wrapper[localScope.value.meta_metadata_name] = localScope.value;
localScope.value = wrapper;
}
return localScope.value;
}
localScope.value = null;
}
return null;
}
Extraction.prototype.extractCompositeCollection = function(field, parentScope) {
var surrogateComposite = null;
if (field.kids instanceof Array && field.kids.length === 1) {
surrogateComposite = field.kids[0].composite;
}
if (!surrogateComposite) {
console.warn("Invalid surrogate composite on %s: %O", field.name, field);
return null;
}
// step 1: prepare local scope for extracting nested fields
var localScope = new Scope(field.name, parentScope);
localScope.field = field;
localScope.contextNode = this.getContextNode(field, parentScope);
localScope.vars = this.handleDefVars(field, localScope);
localScope.value = [];
localScope.count = 0;
var done = false;
// detect and prevent infinite recursion
if (this.isInfiniteRecursion(localScope)) {
return null;
}
// TODO case 1.1: extract from previous field op result
// case 1.2: regular xpath extraction
if (!done && field.xpaths instanceof Array) {
for (var i = 0; i < field.xpaths.length; ++i) {
var xpath = field.xpaths[i];
var xres = this.evaluateAllNodes(xpath, localScope.contextNode, parentScope);
if (xres && xres.snapshotLength > 0) {
localScope.count = xres.snapshotLength;
localScope.nodes = [];
for (var j = 0; j < xres.snapshotLength; ++j) {
localScope.nodes.push(xres.snapshotItem(j));
}
done = true;
break;
}
}
}
// step 2: extract nested fields using newly created local scope
for (var i = 0; i < localScope.count; ++i) {
var localScopei = new Scope('$' + i, localScope);
localScopei.collectionIndex = i+1;
localScopei.node = localScope.nodes[i];
var item = {
meta_metadata_name: surrogateComposite.type || surrogateComposite.name,
};
this.extractFields(surrogateComposite.kids, localScopei, item);
if (Object.keys(item).length > 1) {
if (field.polymorphic_scope || field.polymorphic_classes) {
// TODO change meta_metadata_name based on location
var wrapper = {};
wrapper[item.meta_metadata_name] = item;
item = wrapper;
}
localScope.value.push(item);
}
}
if (done && localScope.value.length > 0) {
return localScope.value;
}
localScope.value = null;
return null;
}
/**
* Recursively extract semantics from contextNode, according to fieldList.
* @param {Array<MetaMetadataField>} fieldList
* The list of nested fields.
* @param {Scope} parentScope
* The lexical scope to store intermediate results.
* @param {metadata} obj
* The result / intermediate metadata object.
*/
Extraction.prototype.extractFields = function(fieldList, parentScope, obj) {
if (fieldList instanceof Array) {
var sorted = [];
for (var i = 0; i < fieldList.length; ++i) {
var field = fieldList[i];
if (this.isScalar(field)) {
sorted.push(field);
}
}
sorted = this.sortFieldsByDependency(sorted);
for (var i = 0; i < fieldList.length; ++i) {
var field = fieldList[i];
if (!this.isScalar(field)) {
sorted.push(field);
}
}
for (var i = 0; i < sorted.length; ++i) {
var field = sorted[i];
var value = null;
if (this.isScalar(field)) {
value = this.extractScalar(field.scalar, parentScope);
}
else if (this.isScalarCollection(field)) {
value = this.extractScalarCollection(field.collection, parentScope);
}
else if (this.isComposite(field)) {
value = this.extractComposite(field.composite, parentScope);
}
else if (this.isCompositeCollection(field)) {
value = this.extractCompositeCollection(field.collection, parentScope);
}
else {
console.warn("Unknown field type: ", field);
}
if (value) {
var unwrapped = this.unwrapField(field);
obj[unwrapped.tag || unwrapped.name] = value;
}
}
}
}
/**
* Unwrap a meta-metadata field.
* @param {MetaMetadataField} field
* @return {Object} The unwrapped field, if `field` is a wrapped
* MetaMetadataField, or the input itself unchanged.
*/
Extraction.prototype.unwrapField = function(field) {
if (field.scalar) {
return field.scalar;
}
if (field.composite) {
return field.composite;
}
if (field.collection) {
return field.collection;
}
return field;
}
/**
* Sort the input list of fields by dependency, i.e. if A depends on B, in the
* output, B precedes A.
* @param {Array<MetaMetadataField>} fieldList
* The list of fields to be sorted.
* @return {Array<MetaMetadataField} The sorted list of fields.
*/
Extraction.prototype.sortFieldsByDependency = function(fieldList) {
if (fieldList instanceof Array) {
var result = [];
var map = {}; // name => field
for (var i = 0; i < fieldList.length; ++i) {
var field = fieldList[i];
map[this.unwrapField(field).name] = field;
}
function forEachDep(field, callback) {
if (field.scalar && field.scalar.concatenate_values instanceof Array) {
for (var i = 0; i < field.concatenate_values.length; ++i) {
var depName = field.concatenate_values[i].from_scalar;
if (depName && depName.length > 0) {
callback(depName);
}
}
}
}
// topological sort
var visited = {}; // name => boolean; used for DFS
var marked = {}; // name => boolean; used to detect cyclic dependencies.
function visit(name) {
var field = map[name];
if (name in marked) {
console.warn("Cyclic dependency among fields detected in %O", fieldList);
return fieldList;
}
if (!(name in visited)) {
marked[name] = true;
forEachDep(field, function(depName) {
visit(depName);
});
delete marked[name];
visited[name] = true;
result.push(field);
}
}
for (var i = 0; i < fieldList.length; ++i) {
var name = this.unwrapField(fieldList[i]).name;
if (!(name in visited)) {
visit(name);
}
}
return result;
}
return fieldList;
}
/**
* Start extraction. Calls callback when finished.
* @param {(err, metadata)=>void} callback
* Callback function to receive result. Result metadata is wrapped.
*/
Extraction.prototype.extract = function(callback) {
this.scope = new Scope('$');
this.scope.field = this.mmd;
this.scope.rootNode = this.rootNode;
this.scope.node = this.rootNode;
this.metadata = {};
this.metadata[this.mmd.tag || this.mmd.name] = this.extractComposite(this.mmd, this.scope);
console.log("Extraction finished: %O", this.metadata);
callback(null, this.metadata);
}
/**
* Extract metadata, given the root DOM element and the meta-metadata.
* @param {Response} resp
* Contains the root DOM element.
* @param {MetaMetadata} mmd
* The wrapper.
* @param {BigSemantics} bsFacade
* Provide BigSemantics functionalities. Nullable.
* @param {Object} options
* Additional options. Nullable.
* @param {(err, metadata)=>void)} callback
* Callback function to receive result. Result metadata is wrapped.
*/
function extractMetadata(resp, mmd, bsFacade, options, callback) {
var extraction = new Extraction(resp, mmd, bsFacade, options);
extraction.extract(callback);
}
/**
* @deprecated
* This is added for debugging. This synchronous version will be removed soon.
* TODO remove this.
*/
function extractMetadataSync(resp, mmd, bsFacade, options) {
var extraction = new Extraction(resp, mmd, bsFacade, options);
extraction.extract(function() {});
return extraction.metadata;
}