jsonldjs 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/index.js CHANGED
@@ -1,390 +1,4 @@
1
- /**
2
- * Custom JSON-LD graph utilities
3
- *
4
- * Simple, focused functions for working with JSON-LD graph arrays.
5
- * No external dependencies, no context expansion - just pure graph traversal.
6
- */
7
- /**
8
- * Find a single entity in the graph by @id
9
- *
10
- * @param graph - Array of JSON-LD entities
11
- * @param id - The @id to search for
12
- * @returns The entity if found, undefined otherwise
13
- */
14
- export function findEntity(graph, id) {
15
- return graph.find(entity => entity['@id'] === id);
16
- }
17
- /**
18
- * Find multiple entities in the graph by @id
19
- *
20
- * @param graph - Array of JSON-LD entities
21
- * @param ids - Array of @ids to search for
22
- * @returns Array of found entities (may be fewer than requested if some not found)
23
- */
24
- export function findEntities(graph, ids) {
25
- const idSet = new Set(ids);
26
- return graph.filter(entity => idSet.has(entity['@id']));
27
- }
28
- /**
29
- * Find entities by @type
30
- *
31
- * @param graph - Array of JSON-LD entities
32
- * @param type - The @type to search for
33
- * @returns Array of entities matching the type
34
- */
35
- export function findEntitiesByType(graph, type) {
36
- return graph.filter(entity => {
37
- const entityType = entity['@type'];
38
- if (Array.isArray(entityType)) {
39
- return entityType.includes(type);
40
- }
41
- return entityType === type;
42
- });
43
- }
44
- /**
45
- * Extract all @id references from an entity's properties
46
- *
47
- * @param entity - JSON-LD entity to scan
48
- * @returns Set of @id strings found in the entity
49
- */
50
- export function extractReferences(entity) {
51
- const references = new Set();
52
- function scanValue(value) {
53
- if (value === null || value === undefined) {
54
- return;
55
- }
56
- if (typeof value === 'string') {
57
- // Check if it looks like an @id reference using regex pattern
58
- // Pattern: ^(?:[a-zA-Z][a-zA-Z0-9+.-]*:)?[^\s]+$
59
- // This matches:
60
- // - URIs with scheme: scheme:path (e.g., mailto:user@example.com)
61
- // - Compact URIs: prefix:suffix (e.g., person:danlynch, org:hyperweb)
62
- // - Must not contain spaces (filters out titles/descriptions with colons)
63
- const idPattern = /^(?:[a-zA-Z][a-zA-Z0-9+.-]*:)[^\s]+$/;
64
- // Additional checks:
65
- // - Must match the pattern
66
- // - Must contain a colon (to be a reference)
67
- // - Exclude http/https URLs (handled separately)
68
- if (idPattern.test(value) && value.includes(':') && !value.startsWith('http')) {
69
- references.add(value);
70
- }
71
- return;
72
- }
73
- if (Array.isArray(value)) {
74
- value.forEach(scanValue);
75
- return;
76
- }
77
- if (typeof value === 'object') {
78
- // If it has an @id, add it
79
- if (value['@id']) {
80
- references.add(value['@id']);
81
- }
82
- // Recursively scan all properties
83
- Object.values(value).forEach(scanValue);
84
- return;
85
- }
86
- }
87
- // Scan all properties except @id and @type
88
- Object.entries(entity).forEach(([key, value]) => {
89
- if (key !== '@id' && key !== '@type') {
90
- scanValue(value);
91
- }
92
- });
93
- return references;
94
- }
95
- /**
96
- * Extract a subgraph containing an entity and all its referenced entities
97
- *
98
- * Recursively finds all @id references within the entity and includes
99
- * those entities in the result. Returns a filtered array of the original
100
- * graph elements - does not modify the entities themselves.
101
- *
102
- * @param graph - Array of JSON-LD entities
103
- * @param id - The root @id to start from
104
- * @returns Array containing the root entity and all recursively referenced entities
105
- */
106
- export function extractSubgraph(graph, id) {
107
- const result = new Map();
108
- const visited = new Set();
109
- const toProcess = new Set([id]);
110
- while (toProcess.size > 0) {
111
- const currentId = toProcess.values().next().value;
112
- toProcess.delete(currentId);
113
- if (visited.has(currentId)) {
114
- continue;
115
- }
116
- visited.add(currentId);
117
- const entity = findEntity(graph, currentId);
118
- if (!entity) {
119
- continue;
120
- }
121
- result.set(currentId, entity);
122
- // Find all references in this entity
123
- const references = extractReferences(entity);
124
- // Add unvisited references to process queue
125
- references.forEach(refId => {
126
- if (!visited.has(refId)) {
127
- toProcess.add(refId);
128
- }
129
- });
130
- }
131
- return Array.from(result.values());
132
- }
133
- /**
134
- * Extract subgraphs for multiple root entities
135
- *
136
- * @param graph - Array of JSON-LD entities
137
- * @param ids - Array of root @ids to start from
138
- * @returns Array containing all entities and their recursively referenced entities
139
- */
140
- export function extractSubgraphs(graph, ids) {
141
- const allEntities = new Map();
142
- ids.forEach(id => {
143
- const subgraph = extractSubgraph(graph, id);
144
- subgraph.forEach(entity => {
145
- allEntities.set(entity['@id'], entity);
146
- });
147
- });
148
- return Array.from(allEntities.values());
149
- }
150
- /**
151
- * Find entities that reference a specific @id
152
- *
153
- * @param graph - Array of JSON-LD entities
154
- * @param targetId - The @id to find references to
155
- * @returns Array of entities that reference the target @id
156
- */
157
- export function findReferencingEntities(graph, targetId) {
158
- return graph.filter(entity => {
159
- const references = extractReferences(entity);
160
- return references.has(targetId);
161
- });
162
- }
163
- /**
164
- * Extract a subgraph with limited depth traversal
165
- *
166
- * Unlike extractSubgraph which recursively follows all references,
167
- * this function only traverses to a specified depth from the root entity.
168
- *
169
- * @param graph - Array of JSON-LD entities
170
- * @param id - The root @id to start from
171
- * @param maxDepth - Maximum depth to traverse (1 = direct references only)
172
- * @returns Array containing entities up to the specified depth
173
- */
174
- export function extractSubgraphWithDepth(graph, id, maxDepth) {
175
- if (maxDepth < 1) {
176
- return [];
177
- }
178
- const result = new Map();
179
- const visited = new Set();
180
- const toProcess = [{ id, depth: 0 }];
181
- while (toProcess.length > 0) {
182
- const current = toProcess.shift();
183
- if (visited.has(current.id) || current.depth > maxDepth) {
184
- continue;
185
- }
186
- visited.add(current.id);
187
- const entity = findEntity(graph, current.id);
188
- if (!entity) {
189
- continue;
190
- }
191
- result.set(current.id, entity);
192
- // Only process references if we haven't reached max depth
193
- if (current.depth < maxDepth) {
194
- const references = extractReferences(entity);
195
- references.forEach(refId => {
196
- if (!visited.has(refId)) {
197
- toProcess.push({ id: refId, depth: current.depth + 1 });
198
- }
199
- });
200
- }
201
- }
202
- return Array.from(result.values());
203
- }
204
- /**
205
- * Find all @id references that don't have corresponding entities in the graph
206
- * @param graph - The JSON-LD graph to analyze
207
- * @returns Array of missing @id references
208
- */
209
- export function findMissingReferences(graph) {
210
- // First, collect all entity @ids that exist in the graph
211
- const existingIds = new Set();
212
- for (const entity of graph) {
213
- if (entity['@id']) {
214
- existingIds.add(entity['@id']);
215
- }
216
- }
217
- // Then, collect all referenced @ids
218
- const allReferences = new Set();
219
- for (const entity of graph) {
220
- const references = extractReferences(entity);
221
- for (const ref of references) {
222
- allReferences.add(ref);
223
- }
224
- }
225
- // Find references that don't exist
226
- const missing = [];
227
- for (const ref of allReferences) {
228
- if (!existingIds.has(ref)) {
229
- missing.push(ref);
230
- }
231
- }
232
- return missing.sort(); // Sort for consistent output
233
- }
234
- /**
235
- * Find entities that contain nested objects (potential normalization candidates)
236
- * @param graph - The JSON-LD graph to analyze
237
- * @returns Array of objects with parent @id and details about nested entities
238
- */
239
- export function findNestedEntities(graph) {
240
- const results = [];
241
- function isNestedEntity(value) {
242
- // Check if it's an object (not null, not array)
243
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
244
- return false;
245
- }
246
- // Skip if it's just an @id reference (only has @id property)
247
- if (Object.keys(value).length === 1 && value['@id']) {
248
- return false;
249
- }
250
- // It's a nested entity if it has properties beyond just @id
251
- return true;
252
- }
253
- function scanEntity(entity, parentId, basePath = '') {
254
- for (const [key, value] of Object.entries(entity)) {
255
- // Skip special JSON-LD properties
256
- if (key.startsWith('@'))
257
- continue;
258
- const propertyPath = basePath ? `${basePath}.${key}` : key;
259
- if (isNestedEntity(value)) {
260
- results.push({
261
- parentId: parentId,
262
- property: propertyPath,
263
- nestedEntity: value,
264
- hasId: !!value['@id']
265
- });
266
- // Recursively scan the nested entity
267
- scanEntity(value, parentId, propertyPath);
268
- }
269
- else if (Array.isArray(value)) {
270
- // Check arrays for nested entities
271
- value.forEach((item, index) => {
272
- if (isNestedEntity(item)) {
273
- const arrayPath = `${propertyPath}[${index}]`;
274
- results.push({
275
- parentId: parentId,
276
- property: arrayPath,
277
- nestedEntity: item,
278
- hasId: !!item['@id']
279
- });
280
- // Recursively scan the nested entity in array
281
- scanEntity(item, parentId, arrayPath);
282
- }
283
- });
284
- }
285
- }
286
- }
287
- for (const entity of graph) {
288
- if (!entity['@id'])
289
- continue;
290
- scanEntity(entity, entity['@id']);
291
- }
292
- return results;
293
- }
294
- /**
295
- * Find all entities that exist in the graph but are never referenced by other entities
296
- * @param graph - The JSON-LD graph to analyze
297
- * @returns Array of orphaned @id values
298
- */
299
- export function findOrphans(graph) {
300
- // First, collect all entity @ids that exist in the graph
301
- const allIds = new Set();
302
- for (const entity of graph) {
303
- if (entity['@id']) {
304
- allIds.add(entity['@id']);
305
- }
306
- }
307
- // Then, collect all referenced @ids
308
- const referencedIds = new Set();
309
- for (const entity of graph) {
310
- const references = extractReferences(entity);
311
- for (const ref of references) {
312
- referencedIds.add(ref);
313
- }
314
- }
315
- // Find entities that exist but are never referenced
316
- const orphans = [];
317
- for (const id of allIds) {
318
- if (!referencedIds.has(id)) {
319
- orphans.push(id);
320
- }
321
- }
322
- return orphans.sort(); // Sort for consistent output
323
- }
324
- /**
325
- * Inline all @id references within entities, replacing them with their full entity data
326
- *
327
- * This function takes an array of entities and recursively replaces all @id references
328
- * with the actual entity data. If a specific root ID is provided, it returns only
329
- * that entity with all its references inlined. Otherwise, it returns all entities
330
- * with references inlined.
331
- *
332
- * @param entities - Array of JSON-LD entities
333
- * @param rootId - Optional root entity @id to return (if not provided, returns all entities)
334
- * @returns Either a single entity with inlined references or array of all entities with inlined references
335
- */
336
- export function inlineReferences(entities, rootId) {
337
- // Create a lookup map for all entities
338
- const entityMap = new Map();
339
- entities.forEach(entity => {
340
- if (entity['@id']) {
341
- entityMap.set(entity['@id'], entity);
342
- }
343
- });
344
- // Function to recursively inline references with circular reference protection
345
- function inlineValue(value, visited = new Set()) {
346
- if (value === null || value === undefined) {
347
- return value;
348
- }
349
- if (Array.isArray(value)) {
350
- return value.map(v => inlineValue(v, visited));
351
- }
352
- if (typeof value === 'object') {
353
- // If it's an @id reference (object with only @id property), replace with the full entity
354
- if (value['@id'] && Object.keys(value).length === 1) {
355
- const id = value['@id'];
356
- // Check for circular reference
357
- if (visited.has(id)) {
358
- // Return just the @id reference to break the cycle
359
- return { '@id': id };
360
- }
361
- const referencedEntity = entityMap.get(id);
362
- if (referencedEntity) {
363
- // Add to visited set before processing
364
- const newVisited = new Set(visited);
365
- newVisited.add(id);
366
- // Create a copy and inline its references
367
- const copy = { ...referencedEntity };
368
- return inlineValue(copy, newVisited);
369
- }
370
- }
371
- // Otherwise, recursively process all properties
372
- const result = {};
373
- for (const [key, val] of Object.entries(value)) {
374
- result[key] = inlineValue(val, visited);
375
- }
376
- return result;
377
- }
378
- return value;
379
- }
380
- // If a root ID is specified, return only that entity with inlined references
381
- if (rootId) {
382
- const mainEntity = entities.find(e => e['@id'] === rootId);
383
- if (!mainEntity) {
384
- throw new Error(`Entity with @id "${rootId}" not found`);
385
- }
386
- return inlineValue(mainEntity);
387
- }
388
- // Otherwise, inline references in all entities
389
- return entities.map(entity => inlineValue(entity));
390
- }
1
+ export { createJsonLdConfig, JsonLdConfigBuilder } from './config';
2
+ export { createJsonLdBuilder, JsonLdBuilder } from './builder';
3
+ export { extractReferences, extractSubgraph, extractSubgraphWithDepth, extractSubgraphs, filterEntityProperties, filterGraphProperties, findEntities, findEntitiesByType, findEntity, findMissingReferences, findNestedEntities, findOrphans, findReferencingEntities, inlineReferences, } from './jsonld-utils';
4
+ export { filterJsonLdGraph } from './builder-utils';