CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-jsonld

A comprehensive JSON-LD Processor and API implementation in JavaScript for processing Linked Data in JSON format

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

context-processing.mddocs/

Context Processing

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.

Capabilities

Process Context

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 upon
  • localCtx (any): Local context to process (can be URL, object, or array)
  • options (ContextOptions, optional): Configuration options

Options:

  • base (string): Base IRI to use (default: empty string)
  • documentLoader (function): Custom document loader for fetching remote contexts
  • safe (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/'
});

Get Context Value (Legacy)

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.

Context Processing Concepts

Active Context Structure

An active context is an internal representation of a processed JSON-LD context that contains:

  • Term definitions: Mappings from terms to IRIs
  • Type mappings: Default types for terms
  • Language mappings: Default language for terms
  • Container mappings: How values should be interpreted (e.g., as sets, lists)
  • Base IRI: The base IRI for relative IRI resolution
  • Vocabulary mapping: Default vocabulary for terms

Context Resolution Process

Context processing involves several steps:

  1. URL Resolution: Remote contexts are fetched using the document loader
  2. Context Merging: Multiple contexts are processed in order
  3. Term Definition: Terms are mapped to IRIs with optional type/language info
  4. Validation: Context structure is validated for correctness
  5. Caching: Resolved contexts may be cached for performance

Context Caching

The library includes internal context caching to improve performance:

  • Resolved contexts are cached based on their URL and processing options
  • Cache size is limited (default: 100 entries)
  • Cache is shared across operations within the same jsonld instance

Advanced Context Processing

Custom Context Resolution

// 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);

Context Validation

// 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);
}

Error Handling in Context Processing

Context processing can fail for various reasons:

  • Invalid context URLs: URL cannot be fetched or is malformed
  • Malformed contexts: Context structure is invalid
  • Circular references: Context includes itself directly or indirectly
  • Network errors: Remote context cannot be loaded
// 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;
  }
};

Types

/**
 * 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
}

docs

context-processing.md

document-loading.md

error-handling.md

event-handling.md

index.md

rdf-operations.md

transformations.md

url-utilities.md

utilities.md

tile.json