-
Notifications
You must be signed in to change notification settings - Fork 64
/
index.js
1392 lines (1178 loc) · 43.8 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
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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Jeremy Whitlock
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
'use strict';
var _ = require('lodash');
var gl = require('graphlib');
var path = require('path');
var PathLoader = require('path-loader');
var qs = require('querystring');
var slash = require('slash');
var URI = require('uri-js');
var badPtrTokenRegex = /~(?:[^01]|$)/g;
var remoteCache = {};
var remoteTypes = ['relative', 'remote'];
var remoteUriTypes = ['absolute', 'uri'];
var uriDetailsCache = {};
// Load promises polyfill if necessary
/* istanbul ignore if */
if (typeof Promise === 'undefined') {
require('native-promise-only');
}
/* Internal Functions */
function combineQueryParams (qs1, qs2) {
var combined = {};
function mergeQueryParams (obj) {
_.forOwn(obj, function (val, key) {
combined[key] = val;
});
}
mergeQueryParams(qs.parse(qs1 || ''));
mergeQueryParams(qs.parse(qs2 || ''));
return Object.keys(combined).length === 0 ? undefined : qs.stringify(combined);
}
function combineURIs (u1, u2) {
// Convert Windows paths
if (_.isString(u1)) {
u1 = slash(u1);
}
if (_.isString(u2)) {
u2 = slash(u2);
}
var u2Details = parseURI(_.isUndefined(u2) ? '' : u2);
var u1Details;
var combinedDetails;
if (remoteUriTypes.indexOf(u2Details.reference) > -1) {
combinedDetails = u2Details;
} else {
u1Details = _.isUndefined(u1) ? undefined : parseURI(u1);
if (!_.isUndefined(u1Details)) {
combinedDetails = u1Details;
// Join the paths
combinedDetails.path = slash(path.join(u1Details.path, u2Details.path));
// Join query parameters
combinedDetails.query = combineQueryParams(u1Details.query, u2Details.query);
} else {
combinedDetails = u2Details;
}
}
// Remove the fragment
combinedDetails.fragment = undefined;
// For relative URIs, add back the '..' since it was removed above
return (remoteUriTypes.indexOf(combinedDetails.reference) === -1 &&
combinedDetails.path.indexOf('../') === 0 ? '../' : '') + URI.serialize(combinedDetails);
}
function findAncestors (obj, path) {
var ancestors = [];
var node;
if (path.length > 0) {
node = obj;
path.slice(0, path.length - 1).forEach(function (seg) {
if (seg in node) {
node = node[seg];
ancestors.push(node);
}
});
}
return ancestors;
}
function isRemote (refDetails) {
return remoteTypes.indexOf(getRefType(refDetails)) > -1;
}
function isValid (refDetails) {
return _.isUndefined(refDetails.error) && refDetails.type !== 'invalid';
}
function findValue (obj, path) {
var value = obj;
// Using this manual approach instead of _.get since we have to decodeURI the segments
path.forEach(function (seg) {
if (seg in value) {
value = value[seg];
} else {
throw Error('JSON Pointer points to missing location: ' + pathToPtr(path));
}
});
return value;
}
function getExtraRefKeys (ref) {
return Object.keys(ref).filter(function (key) {
return key !== '$ref';
});
}
function getRefType (refDetails) {
var type;
// Convert the URI reference to one of our types
switch (refDetails.uriDetails.reference) {
case 'absolute':
case 'uri':
type = 'remote';
break;
case 'same-document':
type = 'local';
break;
default:
type = refDetails.uriDetails.reference;
}
return type;
}
function getRemoteDocument (url, options) {
var cacheEntry = remoteCache[url];
var allTasks = Promise.resolve();
var loaderOptions = _.cloneDeep(options.loaderOptions || {});
if (_.isUndefined(cacheEntry)) {
// If there is no content processor, default to processing the raw response as JSON
if (_.isUndefined(loaderOptions.processContent)) {
loaderOptions.processContent = function (res, callback) {
callback(undefined, JSON.parse(res.text));
};
}
// Attempt to load the resource using path-loader
allTasks = PathLoader.load(decodeURI(url), loaderOptions);
// Update the cache
allTasks = allTasks
.then(function (res) {
remoteCache[url] = {
value: res
};
return res;
})
.catch(function (err) {
remoteCache[url] = {
error: err
};
throw err;
});
} else {
// Return the cached version
allTasks = allTasks.then(function () {
if (_.isError(cacheEntry.error)) {
throw cacheEntry.error;
} else {
return cacheEntry.value;
}
});
}
// Return a cloned version to avoid updating the cache
allTasks = allTasks.then(function (res) {
return _.cloneDeep(res);
});
return allTasks;
}
function isRefLike (obj, throwWithDetails) {
var refLike = true;
try {
if (!_.isPlainObject(obj)) {
throw new Error('obj is not an Object');
} else if (!_.isString(obj.$ref)) {
throw new Error('obj.$ref is not a String');
}
} catch (err) {
if (throwWithDetails) {
throw err;
}
refLike = false;
}
return refLike;
}
function makeAbsolute (location) {
if (location.indexOf('://') === -1 && !path.isAbsolute(location)) {
return path.resolve(process.cwd(), location);
} else {
return location;
}
}
function makeRefFilter (options) {
var refFilter;
var validTypes;
if (_.isArray(options.filter) || _.isString(options.filter)) {
validTypes = _.isString(options.filter) ? [options.filter] : options.filter;
refFilter = function (refDetails) {
// Check the exact type or for invalid URIs, check its original type
return validTypes.indexOf(refDetails.type) > -1 || validTypes.indexOf(getRefType(refDetails)) > -1;
};
} else if (_.isFunction(options.filter)) {
refFilter = options.filter;
} else if (_.isUndefined(options.filter)) {
refFilter = function () {
return true;
};
}
return function (refDetails, path) {
return (refDetails.type !== 'invalid' || options.includeInvalid === true) && refFilter(refDetails, path);
};
}
function makeSubDocPath (options) {
var subDocPath;
if (_.isArray(options.subDocPath)) {
subDocPath = options.subDocPath;
} else if (_.isString(options.subDocPath)) {
subDocPath = pathFromPtr(options.subDocPath);
} else if (_.isUndefined(options.subDocPath)) {
subDocPath = [];
}
return subDocPath;
}
function markMissing (refDetails, err) {
refDetails.error = err.message;
refDetails.missing = true;
}
function parseURI (uri) {
// We decode first to avoid doubly encoding
return URI.parse(uri);
}
function buildRefModel (document, options, metadata) {
var allTasks = Promise.resolve();
var subDocPtr = pathToPtr(options.subDocPath);
var absLocation = makeAbsolute(options.location);
var relativeBase = path.dirname(options.location);
var docDepKey = absLocation + subDocPtr;
var refs;
var rOptions;
// Store the document in the metadata if necessary
if (_.isUndefined(metadata.docs[absLocation])) {
metadata.docs[absLocation] = document;
}
// If there are no dependencies stored for the location+subDocPath, we've never seen it before and will process it
if (_.isUndefined(metadata.deps[docDepKey])) {
metadata.deps[docDepKey] = {};
// Find the references based on the options
refs = findRefs(document, options);
// Iterate over the references and process
_.forOwn(refs, function (refDetails, refPtr) {
var refKey = makeAbsolute(options.location) + refPtr;
var refdKey = refDetails.refdId = decodeURIComponent(makeAbsolute(isRemote(refDetails) ?
combineURIs(relativeBase, refDetails.uri) :
options.location) + '#' +
(refDetails.uri.indexOf('#') > -1 ?
refDetails.uri.split('#')[1] :
''));
// Record reference metadata
metadata.refs[refKey] = refDetails;
// Do not process invalid references
if (!isValid(refDetails)) {
return;
}
// Record the fully-qualified URI
refDetails.fqURI = refdKey;
// Record dependency (relative to the document's sub-document path)
metadata.deps[docDepKey][refPtr === subDocPtr ? '#' : refPtr.replace(subDocPtr + '/', '#/')] = refdKey;
// Do not process directly-circular references (to an ancestor or self)
if (refKey.indexOf(refdKey + '/') === 0 || refKey === refdKey) {
refDetails.circular = true;
return;
}
// Prepare the options for subsequent processDocument calls
rOptions = _.cloneDeep(options);
rOptions.subDocPath = _.isUndefined(refDetails.uriDetails.fragment) ?
[] :
pathFromPtr(decodeURIComponent(refDetails.uriDetails.fragment));
// Resolve the reference
if (isRemote(refDetails)) {
// Delete filter.options because all remote references should be fully resolved
delete rOptions.filter;
// The new location being referenced
rOptions.location = refdKey.split('#')[0];
allTasks = allTasks
.then(function (nMetadata, nOptions) {
return function () {
var rAbsLocation = makeAbsolute(nOptions.location);
var rDoc = nMetadata.docs[rAbsLocation];
if (_.isUndefined(rDoc)) {
// We have no cache so we must retrieve the document
return getRemoteDocument(rAbsLocation, nOptions)
.catch(function (err) {
// Store the response in the document cache
nMetadata.docs[rAbsLocation] = err;
// Return the error to allow the subsequent `then` to handle both errors and successes
return err;
});
} else {
// We have already retrieved (or attempted to) the document and should use the cached version in the
// metadata since it could already be processed some.
return Promise.resolve()
.then(function () {
return rDoc;
});
}
};
}(metadata, rOptions));
} else {
allTasks = allTasks
.then(function () {
return document;
});
}
// Process the remote document or the referenced portion of the local document
allTasks = allTasks
.then(function (nMetadata, nOptions, nRefDetails) {
return function (doc) {
if (_.isError(doc)) {
markMissing(nRefDetails, doc);
} else {
// Wrapped in a try/catch since findRefs throws
try {
return buildRefModel(doc, nOptions, nMetadata)
.catch(function (err) {
markMissing(nRefDetails, err);
});
} catch (err) {
markMissing(nRefDetails, err);
}
}
};
}(metadata, rOptions, refDetails));
});
}
return allTasks;
}
function setValue (obj, refPath, value) {
findValue(obj, refPath.slice(0, refPath.length - 1))[refPath[refPath.length - 1]] = value;
}
function walk (ancestors, node, path, fn) {
var processChildren = true;
function walkItem (item, segment) {
path.push(segment);
walk(ancestors, item, path, fn);
path.pop();
}
// Call the iteratee
if (_.isFunction(fn)) {
processChildren = fn(ancestors, node, path);
}
// We do not process circular objects again
if (ancestors.indexOf(node) === -1) {
ancestors.push(node);
if (processChildren !== false) {
if (_.isArray(node)) {
node.forEach(function (member, index) {
walkItem(member, index.toString());
});
} else if (_.isObject(node)) {
_.forOwn(node, function (cNode, key) {
walkItem(cNode, key);
});
}
}
ancestors.pop();
}
}
function validateOptions (options, obj) {
var locationParts;
var shouldDecode;
if (_.isUndefined(options)) {
// Default to an empty options object
options = {};
} else {
// Clone the options so we do not alter the ones passed in
options = _.cloneDeep(options);
}
if (!_.isObject(options)) {
throw new TypeError('options must be an Object');
} else if (!_.isUndefined(options.resolveCirculars) &&
!_.isBoolean(options.resolveCirculars)) {
throw new TypeError('options.resolveCirculars must be a Boolean');
} else if (!_.isUndefined(options.filter) &&
!_.isArray(options.filter) &&
!_.isFunction(options.filter) &&
!_.isString(options.filter)) {
throw new TypeError('options.filter must be an Array, a Function of a String');
} else if (!_.isUndefined(options.includeInvalid) &&
!_.isBoolean(options.includeInvalid)) {
throw new TypeError('options.includeInvalid must be a Boolean');
} else if (!_.isUndefined(options.location) &&
!_.isString(options.location)) {
throw new TypeError('options.location must be a String');
} else if (!_.isUndefined(options.refPreProcessor) &&
!_.isFunction(options.refPreProcessor)) {
throw new TypeError('options.refPreProcessor must be a Function');
} else if (!_.isUndefined(options.refPostProcessor) &&
!_.isFunction(options.refPostProcessor)) {
throw new TypeError('options.refPostProcessor must be a Function');
} else if (!_.isUndefined(options.subDocPath) &&
!_.isArray(options.subDocPath) &&
!isPtr(options.subDocPath)) {
// If a pointer is provided, throw an error if it's not the proper type
throw new TypeError('options.subDocPath must be an Array of path segments or a valid JSON Pointer');
}
// Default to false for allowing circulars
if (_.isUndefined(options.resolveCirculars)) {
options.resolveCirculars = false;
}
options.filter = makeRefFilter(options);
// options.location is not officially supported yet but will be when Issue 88 is complete
if (_.isUndefined(options.location)) {
options.location = makeAbsolute('./root.json');
}
locationParts = options.location.split('#');
// If options.location contains a fragment, turn it into an options.subDocPath
if (locationParts.length > 1) {
options.subDocPath = '#' + locationParts[1];
}
shouldDecode = decodeURI(options.location) === options.location;
// Just to be safe, remove any accidental fragment as it would break things
options.location = combineURIs(options.location, undefined);
// If the location was not encoded, meke sure it's not when we get it back (Issue #138)
if (shouldDecode) {
options.location = decodeURI(options.location);
}
// Set the subDocPath to avoid everyone else having to compute it
options.subDocPath = makeSubDocPath(options);
if (!_.isUndefined(obj)) {
try {
findValue(obj, options.subDocPath);
} catch (err) {
err.message = err.message.replace('JSON Pointer', 'options.subDocPath');
throw err;
}
}
return options;
}
function decodePath (path) {
if (!_.isArray(path)) {
throw new TypeError('path must be an array');
}
return path.map(function (seg) {
if (!_.isString(seg)) {
seg = JSON.stringify(seg);
}
return seg.replace(/~1/g, '/').replace(/~0/g, '~');
});
}
function encodePath (path) {
if (!_.isArray(path)) {
throw new TypeError('path must be an array');
}
return path.map(function (seg) {
if (!_.isString(seg)) {
seg = JSON.stringify(seg);
}
return seg.replace(/~/g, '~0').replace(/\//g, '~1');
});
}
function findRefs (obj, options) {
var refs = {};
// Validate the provided document
if (!_.isArray(obj) && !_.isObject(obj)) {
throw new TypeError('obj must be an Array or an Object');
}
// Validate options
options = validateOptions(options, obj);
// Walk the document (or sub document) and find all JSON References
walk(findAncestors(obj, options.subDocPath),
findValue(obj, options.subDocPath),
_.cloneDeep(options.subDocPath),
function (ancestors, node, path) {
var processChildren = true;
var refDetails;
var refPtr;
if (isRefLike(node)) {
// Pre-process the node when necessary
if (!_.isUndefined(options.refPreProcessor)) {
node = options.refPreProcessor(_.cloneDeep(node), path);
}
refDetails = getRefDetails(node);
// Post-process the reference details
if (!_.isUndefined(options.refPostProcessor)) {
refDetails = options.refPostProcessor(refDetails, path);
}
if (options.filter(refDetails, path)) {
refPtr = pathToPtr(path);
refs[refPtr] = refDetails;
}
// Whenever a JSON Reference has extra children, its children should not be processed.
// See: http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03#section-3
if (getExtraRefKeys(node).length > 0) {
processChildren = false;
}
}
return processChildren;
});
return refs;
}
function findRefsAt (location, options) {
var allTasks = Promise.resolve();
allTasks = allTasks
.then(function () {
// Validate the provided location
if (!_.isString(location)) {
throw new TypeError('location must be a string');
}
if (_.isUndefined(options)) {
options = {};
}
if (_.isObject(options)) {
// Add the location to the options for processing/validation
options.location = location;
}
// Validate options
options = validateOptions(options);
return getRemoteDocument(options.location, options);
})
.then(function (res) {
var cacheEntry = _.cloneDeep(remoteCache[options.location]);
var cOptions = _.cloneDeep(options);
if (_.isUndefined(cacheEntry.refs)) {
// Do not filter any references so the cache is complete
delete cOptions.filter;
delete cOptions.subDocPath;
cOptions.includeInvalid = true;
remoteCache[options.location].refs = findRefs(res, cOptions);
}
// Add the filter options back
if (!_.isUndefined(options.filter)) {
cOptions.filter = options.filter;
}
// This will use the cache so don't worry about calling it twice
return {
refs: findRefs(res, cOptions),
value: res
};
});
return allTasks;
}
function getRefDetails (obj) {
var details = {
def: obj
};
var cacheKey;
var extraKeys;
var uriDetails;
try {
// This will throw so the result doesn't matter
isRefLike(obj, true);
cacheKey = obj.$ref;
uriDetails = uriDetailsCache[cacheKey];
if (_.isUndefined(uriDetails)) {
uriDetails = uriDetailsCache[cacheKey] = parseURI(cacheKey);
}
details.uri = cacheKey;
details.uriDetails = uriDetails;
if (_.isUndefined(uriDetails.error)) {
details.type = getRefType(details);
// Validate the JSON Pointer
try {
if (['#', '/'].indexOf(cacheKey[0]) > -1) {
isPtr(cacheKey, true);
} else if (cacheKey.indexOf('#') > -1) {
isPtr(uriDetails.fragment, true);
}
} catch (err) {
details.error = err.message;
details.type = 'invalid';
}
} else {
details.error = details.uriDetails.error;
details.type = 'invalid';
}
// Identify warning
extraKeys = getExtraRefKeys(obj);
if (extraKeys.length > 0) {
details.warning = 'Extra JSON Reference properties will be ignored: ' + extraKeys.join(', ');
}
} catch (err) {
details.error = err.message;
details.type = 'invalid';
}
return details;
}
function isPtr (ptr, throwWithDetails) {
var valid = true;
var firstChar;
try {
if (_.isString(ptr)) {
if (ptr !== '') {
firstChar = ptr.charAt(0);
if (['#', '/'].indexOf(firstChar) === -1) {
throw new Error('ptr must start with a / or #/');
} else if (firstChar === '#' && ptr !== '#' && ptr.charAt(1) !== '/') {
throw new Error('ptr must start with a / or #/');
} else if (ptr.match(badPtrTokenRegex)) {
throw new Error('ptr has invalid token(s)');
}
}
} else {
throw new Error('ptr is not a String');
}
} catch (err) {
if (throwWithDetails === true) {
throw err;
}
valid = false;
}
return valid;
}
function isRef (obj, throwWithDetails) {
return isRefLike(obj, throwWithDetails) && getRefDetails(obj).type !== 'invalid';
}
function pathFromPtr (ptr) {
try {
isPtr(ptr, true);
} catch (err) {
throw new Error('ptr must be a JSON Pointer: ' + err.message);
}
var segments = ptr.split('/');
// Remove the first segment
segments.shift();
return decodePath(segments);
}
function pathToPtr (path, hashPrefix) {
if (!_.isArray(path)) {
throw new Error('path must be an Array');
}
// Encode each segment and return
return (hashPrefix !== false ? '#' : '') + (path.length > 0 ? '/' : '') + encodePath(path).join('/');
}
function resolveRefs (obj, options) {
var allTasks = Promise.resolve();
allTasks = allTasks
.then(function () {
// Validate the provided document
if (!_.isArray(obj) && !_.isObject(obj)) {
throw new TypeError('obj must be an Array or an Object');
}
// Validate options
options = validateOptions(options, obj);
// Clone the input so we do not alter it
obj = _.cloneDeep(obj);
})
.then(function () {
var metadata = {
deps: {}, // To avoid processing the same refernece twice, and for circular reference identification
docs: {}, // Cache to avoid processing the same document more than once
refs: {} // Reference locations and their metadata
};
return buildRefModel(obj, options, metadata)
.then(function () {
return metadata;
});
})
.then(function (results) {
var allRefs = {};
var circularPaths = [];
var circulars = [];
var depGraph = new gl.Graph();
var fullLocation = makeAbsolute(options.location);
var refsRoot = fullLocation + pathToPtr(options.subDocPath);
var relativeBase = path.dirname(fullLocation);
// Identify circulars
// Add nodes first
Object.keys(results.deps).forEach(function (node) {
depGraph.setNode(node);
});
// Add edges
_.forOwn(results.deps, function (props, node) {
_.forOwn(props, function (dep) {
depGraph.setEdge(node, dep);
});
});
circularPaths = gl.alg.findCycles(depGraph);
// Create a unique list of circulars
circularPaths.forEach(function (path) {
path.forEach(function (seg) {
if (circulars.indexOf(seg) === -1) {
circulars.push(seg);
}
});
});
// Identify circulars
_.forOwn(results.deps, function (props, node) {
_.forOwn(props, function (dep, prop) {
var isCircular = false;
var refPtr = node + prop.slice(1);
var refDetails = results.refs[node + prop.slice(1)];
var remote = isRemote(refDetails);
var pathIndex;
if (circulars.indexOf(dep) > -1) {
// Figure out if the circular is part of a circular chain or just a reference to a circular
circularPaths.forEach(function (path) {
// Short circuit
if (isCircular) {
return;
}
pathIndex = path.indexOf(dep);
if (pathIndex > -1) {
// Check each path segment to see if the reference location is beneath one of its segments
path.forEach(function (seg) {
// Short circuit
if (isCircular) {
return;
}
if (refPtr.indexOf(seg + '/') === 0) {
// If the reference is local, mark it as circular but if it's a remote reference, only mark it
// circular if the matching path is the last path segment or its match is not to a document root
if (!remote || pathIndex === path.length - 1 || dep[dep.length - 1] !== '#') {
isCircular = true;
}
}
});
}
});
}
if (isCircular) {
// Update all references and reference details
refDetails.circular = true;
}
});
});
// Resolve the references in reverse order since the current order is top-down
_.forOwn(Object.keys(results.deps).reverse(), function (parentPtr) {
var deps = results.deps[parentPtr];
var pPtrParts = parentPtr.split('#');
var pDocument = results.docs[pPtrParts[0]];
var pPtrPath = pathFromPtr(pPtrParts[1]);
_.forOwn(deps, function (dep, prop) {
var depParts = splitFragment(dep);
var dDocument = results.docs[depParts[0]];
var dPtrPath = pPtrPath.concat(pathFromPtr(prop));
var refDetails = results.refs[pPtrParts[0] + pathToPtr(dPtrPath)];
// Resolve reference if valid
if (_.isUndefined(refDetails.error) && _.isUndefined(refDetails.missing)) {
if (!options.resolveCirculars && refDetails.circular) {
refDetails.value = _.cloneDeep(refDetails.def);
} else {
try {
refDetails.value = findValue(dDocument, pathFromPtr(depParts[1]));
} catch (err) {
markMissing(refDetails, err);
return;
}
// If the reference is at the root of the document, replace the document in the cache. Otherwise, replace
// the value in the appropriate location in the document cache.
if (pPtrParts[1] === '' && prop === '#') {
results.docs[pPtrParts[0]] = refDetails.value;
} else {
setValue(pDocument, dPtrPath, refDetails.value);
}
}
}
});
});
function walkRefs (root, refPtr, refPath) {
var refPtrParts = refPtr.split('#');
var refDetails = results.refs[refPtr];
var refDeps;
// Record the reference (relative to the root document unless the reference is in the root document)
allRefs[refPtrParts[0] === options.location ?
'#' + refPtrParts[1] :
pathToPtr(options.subDocPath.concat(refPath))] = refDetails;
// Do not walk invalid references
if (refDetails.circular || !isValid(refDetails)) {
// Sanitize errors
if (!refDetails.circular && refDetails.error) {
// The way we use findRefs now results in an error that doesn't match the expectation
refDetails.error = refDetails.error.replace('options.subDocPath', 'JSON Pointer');
// Update the error to use the appropriate JSON Pointer
if (refDetails.error.indexOf('#') > -1) {
refDetails.error = refDetails.error.replace(refDetails.uri.substr(refDetails.uri.indexOf('#')),
refDetails.uri);
}
// Report errors opening files as JSON Pointer errors
if (refDetails.error.indexOf('ENOENT:') === 0 || refDetails.error.indexOf('Not Found') === 0) {
refDetails.error = 'JSON Pointer points to missing location: ' + refDetails.uri;
}
}
return;
}
refDeps = results.deps[refDetails.refdId];
if (refDetails.refdId.indexOf(root) !== 0) {
Object.keys(refDeps).forEach(function (prop) {
walkRefs(refDetails.refdId, refDetails.refdId + prop.substr(1), refPath.concat(pathFromPtr(prop)));
});
}
}
// For performance reasons, we only process a document (or sub document) and each reference once ever. This means
// that if we want to provide the full picture as to what paths in the resolved document were created as a result
// of a reference, we have to take our fully-qualified reference locations and expand them to be all local based
// on the original document.
Object.keys(results.refs).forEach(function (refPtr) {
var refDetails = results.refs[refPtr];
var fqURISegments;
var uriSegments;
// Make all fully-qualified reference URIs relative to the document root (if necessary). This step is done here
// for performance reasons instead of below when the official sanitization process runs.
if (refDetails.type !== 'invalid') {
// Remove the trailing hash from document root references if they weren't in the original URI
if (refDetails.fqURI[refDetails.fqURI.length - 1] === '#' &&
refDetails.uri[refDetails.uri.length - 1] !== '#') {
refDetails.fqURI = refDetails.fqURI.substr(0, refDetails.fqURI.length - 1);
}
fqURISegments = refDetails.fqURI.split('/');
uriSegments = refDetails.uri.split('/');
// The fully-qualified URI is unencoded so to keep the original formatting of the URI (encoded vs. unencoded),