A comprehensive JSON-LD Processor and API implementation in JavaScript for processing Linked Data in JSON format
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Advanced context processing capabilities for resolving and managing JSON-LD contexts. Context processing is fundamental to JSON-LD operations, handling the resolution of context documents and the creation of active contexts for term expansion and compaction.
Processes a local context, resolving any URLs as necessary, and returns a new active context.
/**
* Processes a local context and returns new active context
* @param activeCtx - The current active context
* @param localCtx - The local context to process
* @param options - Optional configuration object
* @returns Promise resolving to the new active context
*/
function processContext(activeCtx, localCtx, options);Parameters:
activeCtx (any): Current active context to build uponlocalCtx (any): Local context to process (can be URL, object, or array)options (ContextOptions, optional): Configuration optionsOptions:
base (string): Base IRI to use (default: empty string)documentLoader (function): Custom document loader for fetching remote contextssafe (boolean): Use safe mode for context processing (default: false)contextResolver (object): Internal context resolver (advanced usage)Usage Examples:
const jsonld = require('jsonld');
// Basic context processing
const initialContext = {}; // Usually obtained from jsonld internal functions
const localContext = {
"name": "http://schema.org/name",
"Person": "http://schema.org/Person"
};
const activeContext = await jsonld.processContext(initialContext, localContext);
// Process context with URL
const urlContext = "http://schema.org/context";
const activeCtx2 = await jsonld.processContext(initialContext, urlContext, {
documentLoader: customLoader
});
// Process array of contexts
const contextArray = [
"http://schema.org/context",
{"title": "http://purl.org/dc/terms/title"}
];
const activeCtx3 = await jsonld.processContext(initialContext, contextArray);
// Process context with null (returns initial context)
const resetContext = await jsonld.processContext(activeContext, null);
// Process context with safe mode
const safeContext = await jsonld.processContext(initialContext, localContext, {
safe: true,
base: 'http://example.org/'
});Legacy function for retrieving values from processed contexts. This is a backward compatibility function.
/**
* Retrieves a value from a processed context (legacy function)
* @param ctx - The processed context
* @param key - The key to retrieve
* @param type - The type of value to retrieve
* @returns The context value
*/
function getContextValue(ctx, key, type);Note: This is a legacy function maintained for backward compatibility. It's recommended to use the full context processing capabilities instead.
An active context is an internal representation of a processed JSON-LD context that contains:
Context processing involves several steps:
The library includes internal context caching to improve performance:
// Example of pre-processing contexts before use
const preprocessContext = (context) => {
// Add common prefixes
return {
...context,
"schema": "http://schema.org/",
"dc": "http://purl.org/dc/terms/"
};
};
// Use preprocessed context
const localCtx = preprocessContext({
"name": "schema:name",
"title": "dc:title"
});
const processedCtx = await jsonld.processContext({}, localCtx);// Example of validating context before processing
const validateContext = (context) => {
if (typeof context !== 'object' || context === null) {
throw new Error('Context must be an object');
}
// Check for required properties
const requiredTerms = ['name', 'type'];
for (const term of requiredTerms) {
if (!(term in context)) {
throw new Error(`Required term '${term}' missing from context`);
}
}
return context;
};
// Use validated context
try {
const validatedCtx = validateContext(localContext);
const processedCtx = await jsonld.processContext({}, validatedCtx);
} catch (error) {
console.error('Context validation failed:', error.message);
}Context processing can fail for various reasons:
// Robust context processing with error handling
const processContextSafely = async (activeCtx, localCtx, options = {}) => {
try {
return await jsonld.processContext(activeCtx, localCtx, {
...options,
safe: true // Enable safe mode
});
} catch (error) {
if (error.name === 'jsonld.InvalidUrl') {
console.error('Invalid context URL:', error.details.url);
} else if (error.name === 'jsonld.LoadDocumentError') {
console.error('Failed to load context document:', error.details);
} else if (error.name === 'jsonld.InvalidLocalContext') {
console.error('Invalid context structure:', error.details);
} else {
console.error('Context processing error:', error.message);
}
// Return a default context or rethrow based on your needs
throw error;
}
};/**
* Options for context processing operations
*/
interface ContextOptions {
/**
* Base IRI to use for relative IRI resolution
*/
base?: string;
/**
* Custom document loader for fetching remote contexts
*/
documentLoader?: DocumentLoader;
/**
* Use safe mode for context processing
*/
safe?: boolean;
/**
* Internal context resolver (advanced usage)
*/
contextResolver?: any;
}
/**
* Active context structure (internal representation)
*/
interface ActiveContext {
/**
* Base IRI for the context
*/
'@base'?: string;
/**
* Default vocabulary IRI
*/
'@vocab'?: string;
/**
* Default language for string values
*/
'@language'?: string;
/**
* Processing mode version
*/
'@version'?: number;
/**
* Term definitions
*/
mappings: Record<string, TermDefinition>;
/**
* Inverse context for compaction
*/
inverse?: any;
/**
* Previous context in processing chain
*/
previousContext?: ActiveContext;
}
/**
* Term definition structure
*/
interface TermDefinition {
/**
* IRI mapping for the term
*/
'@id'?: string;
/**
* Type mapping for the term
*/
'@type'?: string;
/**
* Language mapping for the term
*/
'@language'?: string;
/**
* Container mapping for the term
*/
'@container'?: string | string[];
/**
* Context for the term (for nested contexts)
*/
'@context'?: any;
/**
* Whether the term is protected from redefinition
*/
'@protected'?: boolean;
/**
* Reverse property flag
*/
'@reverse'?: boolean;
/**
* Prefix flag
*/
'@prefix'?: boolean;
}
/**
* Local context can be various types
*/
type LocalContext =
| string // URL to context
| ContextObject // Context object
| (string | ContextObject)[] // Array of contexts
| null; // Reset to initial context
/**
* Context object structure
*/
interface ContextObject {
'@context'?: LocalContext;
'@base'?: string;
'@vocab'?: string;
'@language'?: string;
'@version'?: number;
[key: string]: any; // Term definitions
}