or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

context-processing.mddocument-loading.mderror-handling.mdevent-handling.mdindex.mdrdf-operations.mdtransformations.mdurl-utilities.mdutilities.md
tile.json

context-processing.mddocs/

0

# Context Processing

1

2

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.

3

4

## Capabilities

5

6

### Process Context

7

8

Processes a local context, resolving any URLs as necessary, and returns a new active context.

9

10

```javascript { .api }

11

/**

12

* Processes a local context and returns new active context

13

* @param activeCtx - The current active context

14

* @param localCtx - The local context to process

15

* @param options - Optional configuration object

16

* @returns Promise resolving to the new active context

17

*/

18

function processContext(activeCtx, localCtx, options);

19

```

20

21

**Parameters:**

22

- `activeCtx` (any): Current active context to build upon

23

- `localCtx` (any): Local context to process (can be URL, object, or array)

24

- `options` (ContextOptions, optional): Configuration options

25

26

**Options:**

27

- `base` (string): Base IRI to use (default: empty string)

28

- `documentLoader` (function): Custom document loader for fetching remote contexts

29

- `safe` (boolean): Use safe mode for context processing (default: false)

30

- `contextResolver` (object): Internal context resolver (advanced usage)

31

32

**Usage Examples:**

33

34

```javascript

35

const jsonld = require('jsonld');

36

37

// Basic context processing

38

const initialContext = {}; // Usually obtained from jsonld internal functions

39

const localContext = {

40

"name": "http://schema.org/name",

41

"Person": "http://schema.org/Person"

42

};

43

44

const activeContext = await jsonld.processContext(initialContext, localContext);

45

46

// Process context with URL

47

const urlContext = "http://schema.org/context";

48

const activeCtx2 = await jsonld.processContext(initialContext, urlContext, {

49

documentLoader: customLoader

50

});

51

52

// Process array of contexts

53

const contextArray = [

54

"http://schema.org/context",

55

{"title": "http://purl.org/dc/terms/title"}

56

];

57

const activeCtx3 = await jsonld.processContext(initialContext, contextArray);

58

59

// Process context with null (returns initial context)

60

const resetContext = await jsonld.processContext(activeContext, null);

61

62

// Process context with safe mode

63

const safeContext = await jsonld.processContext(initialContext, localContext, {

64

safe: true,

65

base: 'http://example.org/'

66

});

67

```

68

69

### Get Context Value (Legacy)

70

71

Legacy function for retrieving values from processed contexts. This is a backward compatibility function.

72

73

```javascript { .api }

74

/**

75

* Retrieves a value from a processed context (legacy function)

76

* @param ctx - The processed context

77

* @param key - The key to retrieve

78

* @param type - The type of value to retrieve

79

* @returns The context value

80

*/

81

function getContextValue(ctx, key, type);

82

```

83

84

**Note:** This is a legacy function maintained for backward compatibility. It's recommended to use the full context processing capabilities instead.

85

86

## Context Processing Concepts

87

88

### Active Context Structure

89

90

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

91

92

- **Term definitions**: Mappings from terms to IRIs

93

- **Type mappings**: Default types for terms

94

- **Language mappings**: Default language for terms

95

- **Container mappings**: How values should be interpreted (e.g., as sets, lists)

96

- **Base IRI**: The base IRI for relative IRI resolution

97

- **Vocabulary mapping**: Default vocabulary for terms

98

99

### Context Resolution Process

100

101

Context processing involves several steps:

102

103

1. **URL Resolution**: Remote contexts are fetched using the document loader

104

2. **Context Merging**: Multiple contexts are processed in order

105

3. **Term Definition**: Terms are mapped to IRIs with optional type/language info

106

4. **Validation**: Context structure is validated for correctness

107

5. **Caching**: Resolved contexts may be cached for performance

108

109

### Context Caching

110

111

The library includes internal context caching to improve performance:

112

113

- Resolved contexts are cached based on their URL and processing options

114

- Cache size is limited (default: 100 entries)

115

- Cache is shared across operations within the same jsonld instance

116

117

## Advanced Context Processing

118

119

### Custom Context Resolution

120

121

```javascript

122

// Example of pre-processing contexts before use

123

const preprocessContext = (context) => {

124

// Add common prefixes

125

return {

126

...context,

127

"schema": "http://schema.org/",

128

"dc": "http://purl.org/dc/terms/"

129

};

130

};

131

132

// Use preprocessed context

133

const localCtx = preprocessContext({

134

"name": "schema:name",

135

"title": "dc:title"

136

});

137

138

const processedCtx = await jsonld.processContext({}, localCtx);

139

```

140

141

### Context Validation

142

143

```javascript

144

// Example of validating context before processing

145

const validateContext = (context) => {

146

if (typeof context !== 'object' || context === null) {

147

throw new Error('Context must be an object');

148

}

149

150

// Check for required properties

151

const requiredTerms = ['name', 'type'];

152

for (const term of requiredTerms) {

153

if (!(term in context)) {

154

throw new Error(`Required term '${term}' missing from context`);

155

}

156

}

157

158

return context;

159

};

160

161

// Use validated context

162

try {

163

const validatedCtx = validateContext(localContext);

164

const processedCtx = await jsonld.processContext({}, validatedCtx);

165

} catch (error) {

166

console.error('Context validation failed:', error.message);

167

}

168

```

169

170

### Error Handling in Context Processing

171

172

Context processing can fail for various reasons:

173

174

- **Invalid context URLs**: URL cannot be fetched or is malformed

175

- **Malformed contexts**: Context structure is invalid

176

- **Circular references**: Context includes itself directly or indirectly

177

- **Network errors**: Remote context cannot be loaded

178

179

```javascript

180

// Robust context processing with error handling

181

const processContextSafely = async (activeCtx, localCtx, options = {}) => {

182

try {

183

return await jsonld.processContext(activeCtx, localCtx, {

184

...options,

185

safe: true // Enable safe mode

186

});

187

} catch (error) {

188

if (error.name === 'jsonld.InvalidUrl') {

189

console.error('Invalid context URL:', error.details.url);

190

} else if (error.name === 'jsonld.LoadDocumentError') {

191

console.error('Failed to load context document:', error.details);

192

} else if (error.name === 'jsonld.InvalidLocalContext') {

193

console.error('Invalid context structure:', error.details);

194

} else {

195

console.error('Context processing error:', error.message);

196

}

197

198

// Return a default context or rethrow based on your needs

199

throw error;

200

}

201

};

202

```

203

204

## Types

205

206

```javascript { .api }

207

/**

208

* Options for context processing operations

209

*/

210

interface ContextOptions {

211

/**

212

* Base IRI to use for relative IRI resolution

213

*/

214

base?: string;

215

216

/**

217

* Custom document loader for fetching remote contexts

218

*/

219

documentLoader?: DocumentLoader;

220

221

/**

222

* Use safe mode for context processing

223

*/

224

safe?: boolean;

225

226

/**

227

* Internal context resolver (advanced usage)

228

*/

229

contextResolver?: any;

230

}

231

232

/**

233

* Active context structure (internal representation)

234

*/

235

interface ActiveContext {

236

/**

237

* Base IRI for the context

238

*/

239

'@base'?: string;

240

241

/**

242

* Default vocabulary IRI

243

*/

244

'@vocab'?: string;

245

246

/**

247

* Default language for string values

248

*/

249

'@language'?: string;

250

251

/**

252

* Processing mode version

253

*/

254

'@version'?: number;

255

256

/**

257

* Term definitions

258

*/

259

mappings: Record<string, TermDefinition>;

260

261

/**

262

* Inverse context for compaction

263

*/

264

inverse?: any;

265

266

/**

267

* Previous context in processing chain

268

*/

269

previousContext?: ActiveContext;

270

}

271

272

/**

273

* Term definition structure

274

*/

275

interface TermDefinition {

276

/**

277

* IRI mapping for the term

278

*/

279

'@id'?: string;

280

281

/**

282

* Type mapping for the term

283

*/

284

'@type'?: string;

285

286

/**

287

* Language mapping for the term

288

*/

289

'@language'?: string;

290

291

/**

292

* Container mapping for the term

293

*/

294

'@container'?: string | string[];

295

296

/**

297

* Context for the term (for nested contexts)

298

*/

299

'@context'?: any;

300

301

/**

302

* Whether the term is protected from redefinition

303

*/

304

'@protected'?: boolean;

305

306

/**

307

* Reverse property flag

308

*/

309

'@reverse'?: boolean;

310

311

/**

312

* Prefix flag

313

*/

314

'@prefix'?: boolean;

315

}

316

317

/**

318

* Local context can be various types

319

*/

320

type LocalContext =

321

| string // URL to context

322

| ContextObject // Context object

323

| (string | ContextObject)[] // Array of contexts

324

| null; // Reset to initial context

325

326

/**

327

* Context object structure

328

*/

329

interface ContextObject {

330

'@context'?: LocalContext;

331

'@base'?: string;

332

'@vocab'?: string;

333

'@language'?: string;

334

'@version'?: number;

335

[key: string]: any; // Term definitions

336

}

337

```