/// <exception cref="JsonLdError"></exception> public static async Task <JObject> CompactAsync(JToken input, JToken context, JsonLdOptions opts) { // 1) // TODO: look into java futures/promises // 2-6) NOTE: these are all the same steps as in expand JToken expanded = await ExpandAsync(input, opts); // 7) if (context is JObject jObj && jObj.ContainsKey("@context")) { context = jObj["@context"]; } var activeCtx = await Context.ParseAsync(context, opts); // 8) var compacted = new JsonLdApi(opts).Compact(activeCtx, null, expanded, opts.GetCompactArrays ()); // final step of Compaction Algorithm // TODO: SPEC: the result result is a NON EMPTY array, if (compacted is JArray jArray) { compacted = jArray.IsEmpty() ? new JObject() : new JObject { [activeCtx.CompactIri("@graph", true)] = compacted } } ; if (!compacted.IsNull() && !context.IsNull()) { if (context is JObject && !((JObject)context).IsEmpty() || context is JArray && !((JArray)context).IsEmpty()) { compacted["@context"] = context; } } // 9) return((JObject)compacted); }
/// <exception cref="JsonLD.Core.JsonLdError"></exception> public static JArray Expand(JToken input, JsonLdOptions opts) { // 1) // TODO: look into java futures/promises // 2) verification of DOMString IRI bool isIriString = input.Type == JTokenType.String; if (isIriString) { bool hasColon = false; foreach (var c in ((string)input)) { if (c == ':') { hasColon = true; } if (!hasColon && (c == '{' || c == '[')) { isIriString = false; break; } } } if (isIriString) { try { RemoteDocument tmp = opts.documentLoader.LoadDocument((string)input); input = tmp.document; } catch (Exception e) { // TODO: figure out how to deal with remote context throw new JsonLdError(JsonLdError.Error.LoadingDocumentFailed, e.Message); } // if set the base in options should override the base iri in the // active context // thus only set this as the base iri if it's not already set in // options if (opts.GetBase() == null) { opts.SetBase((string)input); } } // 3) Context activeCtx = new Context(opts); // 4) if (opts.GetExpandContext() != null) { JObject exCtx = opts.GetExpandContext(); if (exCtx is JObject && ((IDictionary <string, JToken>)exCtx).ContainsKey("@context" )) { exCtx = (JObject)((IDictionary <string, JToken>)exCtx)["@context"]; } activeCtx = activeCtx.Parse(exCtx); } // 5) // TODO: add support for getting a context from HTTP when content-type // is set to a jsonld compatable format // 6) JToken expanded = new JsonLdApi(opts).Expand(activeCtx, input); // final step of Expansion Algorithm if (expanded is JObject && ((IDictionary <string, JToken>)expanded).ContainsKey("@graph") && ( (IDictionary <string, JToken>)expanded).Count == 1) { expanded = ((JObject)expanded)["@graph"]; } else { if (expanded.IsNull()) { expanded = new JArray(); } } // normalize to an array if (!(expanded is JArray)) { JArray tmp = new JArray(); tmp.Add(expanded); expanded = tmp; } return((JArray)expanded); }