-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathjsonld.js
6998 lines (6361 loc) · 195 KB
/
jsonld.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
/**
* A JavaScript implementation of the JSON-LD API.
*
* @author Dave Longley
*
* BSD 3-Clause License
* Copyright (c) 2011-2013 Digital Bazaar, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of the Digital Bazaar, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function() {
// determine if in-browser or using node.js
var _nodejs = (
typeof process !== 'undefined' && process.versions && process.versions.node);
var _browser = !_nodejs &&
(typeof window !== 'undefined' || typeof self !== 'undefined');
if(_browser) {
if(typeof global === 'undefined') {
if(typeof window !== 'undefined') {
global = window;
}
else if(typeof self !== 'undefined') {
global = self;
}
else if(typeof $ !== 'undefined') {
global = $;
}
}
}
// attaches jsonld API to the given object
var wrapper = function(jsonld) {
/* Core API */
/**
* Performs JSON-LD compaction.
*
* @param input the JSON-LD input to compact.
* @param ctx the context to compact with.
* @param [options] options to use:
* [base] the base IRI to use.
* [compactArrays] true to compact arrays to single values when
* appropriate, false not to (default: true).
* [graph] true to always output a top-level graph (default: false).
* [expandContext] a context to expand with.
* [skipExpansion] true to assume the input is expanded and skip
* expansion, false not to, defaults to false.
* [documentLoader(url, callback(err, remoteDoc))] the document loader.
* @param callback(err, compacted, ctx) called once the operation completes.
*/
jsonld.compact = function(input, ctx, options, callback) {
if(arguments.length < 2) {
return jsonld.nextTick(function() {
callback(new TypeError('Could not compact, too few arguments.'));
});
}
// get arguments
if(typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
if(ctx === null) {
return jsonld.nextTick(function() {
callback(new JsonLdError(
'The compaction context must not be null.',
'jsonld.CompactError', {code: 'invalid local context'}));
});
}
// nothing to compact
if(input === null) {
return jsonld.nextTick(function() {
callback(null, null);
});
}
// set default options
if(!('base' in options)) {
options.base = (typeof input === 'string') ? input : '';
}
if(!('compactArrays' in options)) {
options.compactArrays = true;
}
if(!('graph' in options)) {
options.graph = false;
}
if(!('skipExpansion' in options)) {
options.skipExpansion = false;
}
if(!('documentLoader' in options)) {
options.documentLoader = jsonld.loadDocument;
}
var expand = function(input, options, callback) {
jsonld.nextTick(function() {
if(options.skipExpansion) {
return callback(null, input);
}
jsonld.expand(input, options, callback);
});
};
// expand input then do compaction
expand(input, options, function(err, expanded) {
if(err) {
return callback(new JsonLdError(
'Could not expand input before compaction.',
'jsonld.CompactError', {cause: err}));
}
// process context
var activeCtx = _getInitialContext(options);
jsonld.processContext(activeCtx, ctx, options, function(err, activeCtx) {
if(err) {
return callback(new JsonLdError(
'Could not process context before compaction.',
'jsonld.CompactError', {cause: err}));
}
var compacted;
try {
// do compaction
compacted = new Processor().compact(
activeCtx, null, expanded, options);
}
catch(ex) {
return callback(ex);
}
cleanup(null, compacted, activeCtx, options);
});
});
// performs clean up after compaction
function cleanup(err, compacted, activeCtx, options) {
if(err) {
return callback(err);
}
if(options.compactArrays && !options.graph && _isArray(compacted)) {
// simplify to a single item
if(compacted.length === 1) {
compacted = compacted[0];
}
// simplify to an empty object
else if(compacted.length === 0) {
compacted = {};
}
}
// always use array if graph option is on
else if(options.graph && _isObject(compacted)) {
compacted = [compacted];
}
// follow @context key
if(_isObject(ctx) && '@context' in ctx) {
ctx = ctx['@context'];
}
// build output context
ctx = _clone(ctx);
if(!_isArray(ctx)) {
ctx = [ctx];
}
// remove empty contexts
var tmp = ctx;
ctx = [];
for(var i = 0; i < tmp.length; ++i) {
if(!_isObject(tmp[i]) || Object.keys(tmp[i]).length > 0) {
ctx.push(tmp[i]);
}
}
// remove array if only one context
var hasContext = (ctx.length > 0);
if(ctx.length === 1) {
ctx = ctx[0];
}
// add context and/or @graph
if(_isArray(compacted)) {
// use '@graph' keyword
var kwgraph = _compactIri(activeCtx, '@graph');
var graph = compacted;
compacted = {};
if(hasContext) {
compacted['@context'] = ctx;
}
compacted[kwgraph] = graph;
}
else if(_isObject(compacted) && hasContext) {
// reorder keys so @context is first
var graph = compacted;
compacted = {'@context': ctx};
for(var key in graph) {
compacted[key] = graph[key];
}
}
callback(null, compacted, activeCtx);
}
};
/**
* Performs JSON-LD expansion.
*
* @param input the JSON-LD input to expand.
* @param [options] the options to use:
* [base] the base IRI to use.
* [expandContext] a context to expand with.
* [keepFreeFloatingNodes] true to keep free-floating nodes,
* false not to, defaults to false.
* [documentLoader(url, callback(err, remoteDoc))] the document loader.
* @param callback(err, expanded) called once the operation completes.
*/
jsonld.expand = function(input, options, callback) {
if(arguments.length < 1) {
return jsonld.nextTick(function() {
callback(new TypeError('Could not expand, too few arguments.'));
});
}
// get arguments
if(typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
// set default options
if(!('documentLoader' in options)) {
options.documentLoader = jsonld.loadDocument;
}
if(!('keepFreeFloatingNodes' in options)) {
options.keepFreeFloatingNodes = false;
}
jsonld.nextTick(function() {
// if input is a string, attempt to dereference remote document
if(typeof input === 'string') {
var done = function(err, remoteDoc) {
if(err) {
return callback(err);
}
try {
if(!remoteDoc.document) {
throw new JsonLdError(
'No remote document found at the given URL.',
'jsonld.NullRemoteDocument');
}
if(typeof remoteDoc.document === 'string') {
remoteDoc.document = JSON.parse(remoteDoc.document);
}
}
catch(ex) {
return callback(new JsonLdError(
'Could not retrieve a JSON-LD document from the URL. URL ' +
'dereferencing not implemented.', 'jsonld.LoadDocumentError', {
code: 'loading document failed',
cause: ex,
remoteDoc: remoteDoc
}));
}
expand(remoteDoc);
};
var promise = options.documentLoader(input, done);
if(promise && 'then' in promise) {
promise.then(done.bind(null, null), done);
}
return;
}
// nothing to load
expand({contextUrl: null, documentUrl: null, document: input});
});
function expand(remoteDoc) {
// set default base
if(!('base' in options)) {
options.base = remoteDoc.documentUrl || '';
}
// build meta-object and retrieve all @context URLs
var input = {
document: _clone(remoteDoc.document),
remoteContext: {'@context': remoteDoc.contextUrl}
};
if('expandContext' in options) {
var expandContext = _clone(options.expandContext);
if(typeof expandContext === 'object' && '@context' in expandContext) {
input.expandContext = expandContext;
}
else {
input.expandContext = {'@context': expandContext};
}
}
_retrieveContextUrls(input, options, function(err, input) {
if(err) {
return callback(err);
}
var expanded;
try {
var processor = new Processor();
var activeCtx = _getInitialContext(options);
var document = input.document;
var remoteContext = input.remoteContext['@context'];
// process optional expandContext
if(input.expandContext) {
activeCtx = processor.processContext(
activeCtx, input.expandContext['@context'], options);
}
// process remote context from HTTP Link Header
if(remoteContext) {
activeCtx = processor.processContext(
activeCtx, remoteContext, options);
}
// expand document
expanded = processor.expand(
activeCtx, null, document, options, false);
// optimize away @graph with no other properties
if(_isObject(expanded) && ('@graph' in expanded) &&
Object.keys(expanded).length === 1) {
expanded = expanded['@graph'];
}
else if(expanded === null) {
expanded = [];
}
// normalize to an array
if(!_isArray(expanded)) {
expanded = [expanded];
}
}
catch(ex) {
return callback(ex);
}
callback(null, expanded);
});
}
};
/**
* Performs JSON-LD flattening.
*
* @param input the JSON-LD to flatten.
* @param ctx the context to use to compact the flattened output, or null.
* @param [options] the options to use:
* [base] the base IRI to use.
* [expandContext] a context to expand with.
* [documentLoader(url, callback(err, remoteDoc))] the document loader.
* @param callback(err, flattened) called once the operation completes.
*/
jsonld.flatten = function(input, ctx, options, callback) {
if(arguments.length < 1) {
return jsonld.nextTick(function() {
callback(new TypeError('Could not flatten, too few arguments.'));
});
}
// get arguments
if(typeof options === 'function') {
callback = options;
options = {};
}
else if(typeof ctx === 'function') {
callback = ctx;
ctx = null;
options = {};
}
options = options || {};
// set default options
if(!('base' in options)) {
options.base = (typeof input === 'string') ? input : '';
}
if(!('documentLoader' in options)) {
options.documentLoader = jsonld.loadDocument;
}
// expand input
jsonld.expand(input, options, function(err, _input) {
if(err) {
return callback(new JsonLdError(
'Could not expand input before flattening.',
'jsonld.FlattenError', {cause: err}));
}
var flattened;
try {
// do flattening
flattened = new Processor().flatten(_input);
}
catch(ex) {
return callback(ex);
}
if(ctx === null) {
return callback(null, flattened);
}
// compact result (force @graph option to true, skip expansion)
options.graph = true;
options.skipExpansion = true;
jsonld.compact(flattened, ctx, options, function(err, compacted) {
if(err) {
return callback(new JsonLdError(
'Could not compact flattened output.',
'jsonld.FlattenError', {cause: err}));
}
callback(null, compacted);
});
});
};
/**
* Performs JSON-LD framing.
*
* @param input the JSON-LD input to frame.
* @param frame the JSON-LD frame to use.
* @param [options] the framing options.
* [base] the base IRI to use.
* [expandContext] a context to expand with.
* [embed] default @embed flag (default: true).
* [explicit] default @explicit flag (default: false).
* [omitDefault] default @omitDefault flag (default: false).
* [documentLoader(url, callback(err, remoteDoc))] the document loader.
* @param callback(err, framed) called once the operation completes.
*/
jsonld.frame = function(input, frame, options, callback) {
if(arguments.length < 2) {
return jsonld.nextTick(function() {
callback(new TypeError('Could not frame, too few arguments.'));
});
}
// get arguments
if(typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
// set default options
if(!('base' in options)) {
options.base = (typeof input === 'string') ? input : '';
}
if(!('documentLoader' in options)) {
options.documentLoader = jsonld.loadDocument;
}
if(!('embed' in options)) {
options.embed = true;
}
options.explicit = options.explicit || false;
options.omitDefault = options.omitDefault || false;
jsonld.nextTick(function() {
// if frame is a string, attempt to dereference remote document
if(typeof frame === 'string') {
var done = function(err, remoteDoc) {
if(err) {
return callback(err);
}
try {
if(!remoteDoc.document) {
throw new JsonLdError(
'No remote document found at the given URL.',
'jsonld.NullRemoteDocument');
}
if(typeof remoteDoc.document === 'string') {
remoteDoc.document = JSON.parse(remoteDoc.document);
}
}
catch(ex) {
return callback(new JsonLdError(
'Could not retrieve a JSON-LD document from the URL. URL ' +
'dereferencing not implemented.', 'jsonld.LoadDocumentError', {
code: 'loading document failed',
cause: ex,
remoteDoc: remoteDoc
}));
}
doFrame(remoteDoc);
};
var promise = options.documentLoader(frame, done);
if(promise && 'then' in promise) {
promise.then(done.bind(null, null), done);
}
return;
}
// nothing to load
doFrame({contextUrl: null, documentUrl: null, document: frame});
});
function doFrame(remoteFrame) {
// preserve frame context and add any Link header context
var frame = remoteFrame.document;
var ctx;
if(frame) {
ctx = frame['@context'];
if(remoteFrame.contextUrl) {
if(!ctx) {
ctx = remoteFrame.contextUrl;
}
else if(_isArray(ctx)) {
ctx.push(remoteFrame.contextUrl);
}
else {
ctx = [ctx, remoteFrame.contextUrl];
}
frame['@context'] = ctx;
}
else {
ctx = ctx || {};
}
}
else {
ctx = {};
}
// expand input
jsonld.expand(input, options, function(err, expanded) {
if(err) {
return callback(new JsonLdError(
'Could not expand input before framing.',
'jsonld.FrameError', {cause: err}));
}
// expand frame
var opts = _clone(options);
opts.isFrame = true;
opts.keepFreeFloatingNodes = true;
jsonld.expand(frame, opts, function(err, expandedFrame) {
if(err) {
return callback(new JsonLdError(
'Could not expand frame before framing.',
'jsonld.FrameError', {cause: err}));
}
var framed;
try {
// do framing
framed = new Processor().frame(expanded, expandedFrame, opts);
}
catch(ex) {
return callback(ex);
}
// compact result (force @graph option to true, skip expansion)
opts.graph = true;
opts.skipExpansion = true;
jsonld.compact(framed, ctx, opts, function(err, compacted, ctx) {
if(err) {
return callback(new JsonLdError(
'Could not compact framed output.',
'jsonld.FrameError', {cause: err}));
}
// get graph alias
var graph = _compactIri(ctx, '@graph');
// remove @preserve from results
compacted[graph] = _removePreserve(ctx, compacted[graph], opts);
callback(null, compacted);
});
});
});
}
};
/**
* Performs JSON-LD objectification.
*
* @param input the JSON-LD input to objectify.
* @param ctx the JSON-LD context to apply.
* @param [options] the framing options.
* [base] the base IRI to use.
* [expandContext] a context to expand with.
* [documentLoader(url, callback(err, remoteDoc))] the document loader.
* @param callback(err, objectified) called once the operation completes.
*/
jsonld.objectify = function(input, ctx, options, callback) {
// get arguments
if(typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
// set default options
if(!('base' in options)) {
options.base = (typeof input === 'string') ? input : '';
}
if(!('documentLoader' in options)) {
options.documentLoader = jsonld.loadDocument;
}
// expand input
jsonld.expand(input, options, function(err, _input) {
if(err) {
return callback(new JsonLdError(
'Could not expand input before framing.',
'jsonld.FrameError', {cause: err}));
}
var flattened;
try {
// flatten the graph
flattened = new Processor().flatten(_input);
}
catch(ex) {
return callback(ex);
}
// compact result (force @graph option to true, skip expansion)
options.graph = true;
options.skipExpansion = true;
jsonld.compact(flattened, ctx, options, function(err, compacted, ctx) {
if(err) {
return callback(new JsonLdError(
'Could not compact flattened output.',
'jsonld.FrameError', {cause: err}));
}
// get graph alias
var graph = _compactIri(ctx, '@graph');
// remove @preserve from results (named graphs?)
compacted[graph] = _removePreserve(ctx, compacted[graph], options);
var top = compacted[graph][0];
var recurse = function(subject) {
// can't replace just a string
if(!_isObject(subject) && !_isArray(subject)) {
return;
}
// bottom out recursion on re-visit
if(_isObject(subject)) {
if(recurse.visited[subject['@id']]) {
return;
}
recurse.visited[subject['@id']] = true;
}
// each array element *or* object key
for(var k in subject) {
var obj = subject[k];
var isid = (jsonld.getContextValue(ctx, k, '@type') === '@id');
// can't replace a non-object or non-array unless it's an @id
if(!_isArray(obj) && !_isObject(obj) && !isid) {
continue;
}
if(_isString(obj) && isid) {
subject[k] = obj = top[obj];
recurse(obj);
}
else if(_isArray(obj)) {
for(var i = 0; i < obj.length; ++i) {
if(_isString(obj[i]) && isid) {
obj[i] = top[obj[i]];
}
else if(_isObject(obj[i]) && '@id' in obj[i]) {
obj[i] = top[obj[i]['@id']];
}
recurse(obj[i]);
}
}
else if(_isObject(obj)) {
var sid = obj['@id'];
subject[k] = obj = top[sid];
recurse(obj);
}
}
};
recurse.visited = {};
recurse(top);
compacted.of_type = {};
for(var s in top) {
if(!('@type' in top[s])) {
continue;
}
var types = top[s]['@type'];
if(!_isArray(types)) {
types = [types];
}
for(var t in types) {
if(!(types[t] in compacted.of_type)) {
compacted.of_type[types[t]] = [];
}
compacted.of_type[types[t]].push(top[s]);
}
}
callback(null, compacted);
});
});
};
/**
* Performs RDF dataset normalization on the given JSON-LD input. The output
* is an RDF dataset unless the 'format' option is used.
*
* @param input the JSON-LD input to normalize.
* @param [options] the options to use:
* [base] the base IRI to use.
* [expandContext] a context to expand with.
* [format] the format if output is a string:
* 'application/nquads' for N-Quads.
* [documentLoader(url, callback(err, remoteDoc))] the document loader.
* @param callback(err, normalized) called once the operation completes.
*/
jsonld.normalize = function(input, options, callback) {
if(arguments.length < 1) {
return jsonld.nextTick(function() {
callback(new TypeError('Could not normalize, too few arguments.'));
});
}
// get arguments
if(typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
// set default options
if(!('base' in options)) {
options.base = (typeof input === 'string') ? input : '';
}
if(!('documentLoader' in options)) {
options.documentLoader = jsonld.loadDocument;
}
// convert to RDF dataset then do normalization
var opts = _clone(options);
delete opts.format;
opts.produceGeneralizedRdf = false;
jsonld.toRDF(input, opts, function(err, dataset) {
if(err) {
return callback(new JsonLdError(
'Could not convert input to RDF dataset before normalization.',
'jsonld.NormalizeError', {cause: err}));
}
// do normalization
new Processor().normalize(dataset, options, callback);
});
};
/**
* Converts an RDF dataset to JSON-LD.
*
* @param dataset a serialized string of RDF in a format specified by the
* format option or an RDF dataset to convert.
* @param [options] the options to use:
* [format] the format if dataset param must first be parsed:
* 'application/nquads' for N-Quads (default).
* [rdfParser] a custom RDF-parser to use to parse the dataset.
* [useRdfType] true to use rdf:type, false to use @type
* (default: false).
* [useNativeTypes] true to convert XSD types into native types
* (boolean, integer, double), false not to (default: false).
* @param callback(err, output) called once the operation completes.
*/
jsonld.fromRDF = function(dataset, options, callback) {
if(arguments.length < 1) {
return jsonld.nextTick(function() {
callback(new TypeError('Could not convert from RDF, too few arguments.'));
});
}
// get arguments
if(typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
// set default options
if(!('useRdfType' in options)) {
options.useRdfType = false;
}
if(!('useNativeTypes' in options)) {
options.useNativeTypes = false;
}
if(!('format' in options) && _isString(dataset)) {
// set default format to nquads
if(!('format' in options)) {
options.format = 'application/nquads';
}
}
jsonld.nextTick(function() {
// handle special format
var rdfParser;
if(options.format) {
// check supported formats
rdfParser = options.rdfParser || _rdfParsers[options.format];
if(!rdfParser) {
return callback(new JsonLdError(
'Unknown input format.',
'jsonld.UnknownFormat', {format: options.format}));
}
}
else {
// no-op parser, assume dataset already parsed
rdfParser = function() {
return dataset;
};
}
// rdf parser may be async or sync, always pass callback
dataset = rdfParser(dataset, function(err, dataset) {
if(err) {
return callback(err);
}
fromRDF(dataset, options, callback);
});
// handle synchronous or promise-based parser
if(dataset) {
// if dataset is actually a promise
if('then' in dataset) {
return dataset.then(function(dataset) {
fromRDF(dataset, options, callback);
}, callback);
}
// parser is synchronous
fromRDF(dataset, options, callback);
}
function fromRDF(dataset, options, callback) {
// convert from RDF
new Processor().fromRDF(dataset, options, callback);
}
});
};
/**
* Outputs the RDF dataset found in the given JSON-LD object.
*
* @param input the JSON-LD input.
* @param [options] the options to use:
* [base] the base IRI to use.
* [expandContext] a context to expand with.
* [format] the format to use to output a string:
* 'application/nquads' for N-Quads.
* [produceGeneralizedRdf] true to output generalized RDF, false
* to produce only standard RDF (default: false).
* [documentLoader(url, callback(err, remoteDoc))] the document loader.
* @param callback(err, dataset) called once the operation completes.
*/
jsonld.toRDF = function(input, options, callback) {
if(arguments.length < 1) {
return jsonld.nextTick(function() {
callback(new TypeError('Could not convert to RDF, too few arguments.'));
});
}
// get arguments
if(typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
// set default options
if(!('base' in options)) {
options.base = (typeof input === 'string') ? input : '';
}
if(!('documentLoader' in options)) {
options.documentLoader = jsonld.loadDocument;
}
// expand input
jsonld.expand(input, options, function(err, expanded) {
if(err) {
return callback(new JsonLdError(
'Could not expand input before serialization to RDF.',
'jsonld.RdfError', {cause: err}));
}
var dataset;
try {
// output RDF dataset
dataset = Processor.prototype.toRDF(expanded, options);
if(options.format) {
if(options.format === 'application/nquads') {
return callback(null, _toNQuads(dataset));
}
throw new JsonLdError(
'Unknown output format.',
'jsonld.UnknownFormat', {format: options.format});
}
}
catch(ex) {
return callback(ex);
}
callback(null, dataset);
});
};
/**
* Relabels all blank nodes in the given JSON-LD input.
*
* @param input the JSON-LD input.
*/
jsonld.relabelBlankNodes = function(input) {
_labelBlankNodes(new UniqueNamer('_:b', input));
};
/**
* The default document loader for external documents. If the environment
* is node.js, a callback-continuation-style document loader is used; otherwise,
* a promises-style document loader is used.
*
* @param url the URL to load.
* @param callback(err, remoteDoc) called once the operation completes,
* if using a non-promises API.
*
* @return a promise, if using a promises API.
*/
jsonld.documentLoader = function(url, callback) {
var err = new JsonLdError(
'Could not retrieve a JSON-LD document from the URL. URL ' +
'dereferencing not implemented.', 'jsonld.LoadDocumentError',
{code: 'loading document failed'});
if(_nodejs) {
return callback(err, {contextUrl: null, documentUrl: url, document: null});
}
return jsonld.promisify(function(callback) {
callback(err);
});
};
/**
* Deprecated default document loader. Use or override jsonld.documentLoader
* instead.
*/
jsonld.loadDocument = function(url, callback) {
var promise = jsonld.documentLoader(url, callback);
if(promise && 'then' in promise) {
promise.then(callback.bind(null, null), callback);
}
};
/* Promises API */
jsonld.promises = function() {
var slice = Array.prototype.slice;
var promisify = jsonld.promisify;
var api = {};
api.expand = function(input) {
if(arguments.length < 1) {
throw new TypeError('Could not expand, too few arguments.');
}
return promisify.apply(null, [jsonld.expand].concat(slice.call(arguments)));
};
api.compact = function(input, ctx) {
if(arguments.length < 2) {
throw new TypeError('Could not compact, too few arguments.');
}
var compact = function(input, ctx, options, callback) {
// ensure only one value is returned in callback
jsonld.compact(input, ctx, options, function(err, compacted) {
callback(err, compacted);
});