jsonldjs 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # jsonldjs
package/esm/index.js ADDED
@@ -0,0 +1,390 @@
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
+ }
package/index.d.ts ADDED
@@ -0,0 +1,119 @@
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
+ export type JsonLdEntity = {
8
+ '@id': string;
9
+ '@type'?: string | string[];
10
+ [key: string]: any;
11
+ };
12
+ export type JsonLdGraph = JsonLdEntity[];
13
+ /**
14
+ * Find a single entity in the graph by @id
15
+ *
16
+ * @param graph - Array of JSON-LD entities
17
+ * @param id - The @id to search for
18
+ * @returns The entity if found, undefined otherwise
19
+ */
20
+ export declare function findEntity(graph: JsonLdGraph, id: string): JsonLdEntity | undefined;
21
+ /**
22
+ * Find multiple entities in the graph by @id
23
+ *
24
+ * @param graph - Array of JSON-LD entities
25
+ * @param ids - Array of @ids to search for
26
+ * @returns Array of found entities (may be fewer than requested if some not found)
27
+ */
28
+ export declare function findEntities(graph: JsonLdGraph, ids: string[]): JsonLdEntity[];
29
+ /**
30
+ * Find entities by @type
31
+ *
32
+ * @param graph - Array of JSON-LD entities
33
+ * @param type - The @type to search for
34
+ * @returns Array of entities matching the type
35
+ */
36
+ export declare function findEntitiesByType(graph: JsonLdGraph, type: string): JsonLdEntity[];
37
+ /**
38
+ * Extract all @id references from an entity's properties
39
+ *
40
+ * @param entity - JSON-LD entity to scan
41
+ * @returns Set of @id strings found in the entity
42
+ */
43
+ export declare function extractReferences(entity: JsonLdEntity): Set<string>;
44
+ /**
45
+ * Extract a subgraph containing an entity and all its referenced entities
46
+ *
47
+ * Recursively finds all @id references within the entity and includes
48
+ * those entities in the result. Returns a filtered array of the original
49
+ * graph elements - does not modify the entities themselves.
50
+ *
51
+ * @param graph - Array of JSON-LD entities
52
+ * @param id - The root @id to start from
53
+ * @returns Array containing the root entity and all recursively referenced entities
54
+ */
55
+ export declare function extractSubgraph(graph: JsonLdGraph, id: string): JsonLdEntity[];
56
+ /**
57
+ * Extract subgraphs for multiple root entities
58
+ *
59
+ * @param graph - Array of JSON-LD entities
60
+ * @param ids - Array of root @ids to start from
61
+ * @returns Array containing all entities and their recursively referenced entities
62
+ */
63
+ export declare function extractSubgraphs(graph: JsonLdGraph, ids: string[]): JsonLdEntity[];
64
+ /**
65
+ * Find entities that reference a specific @id
66
+ *
67
+ * @param graph - Array of JSON-LD entities
68
+ * @param targetId - The @id to find references to
69
+ * @returns Array of entities that reference the target @id
70
+ */
71
+ export declare function findReferencingEntities(graph: JsonLdGraph, targetId: string): JsonLdEntity[];
72
+ /**
73
+ * Extract a subgraph with limited depth traversal
74
+ *
75
+ * Unlike extractSubgraph which recursively follows all references,
76
+ * this function only traverses to a specified depth from the root entity.
77
+ *
78
+ * @param graph - Array of JSON-LD entities
79
+ * @param id - The root @id to start from
80
+ * @param maxDepth - Maximum depth to traverse (1 = direct references only)
81
+ * @returns Array containing entities up to the specified depth
82
+ */
83
+ export declare function extractSubgraphWithDepth(graph: JsonLdGraph, id: string, maxDepth: number): JsonLdEntity[];
84
+ /**
85
+ * Find all @id references that don't have corresponding entities in the graph
86
+ * @param graph - The JSON-LD graph to analyze
87
+ * @returns Array of missing @id references
88
+ */
89
+ export declare function findMissingReferences(graph: JsonLdGraph): string[];
90
+ /**
91
+ * Find entities that contain nested objects (potential normalization candidates)
92
+ * @param graph - The JSON-LD graph to analyze
93
+ * @returns Array of objects with parent @id and details about nested entities
94
+ */
95
+ export declare function findNestedEntities(graph: JsonLdGraph): Array<{
96
+ parentId: string;
97
+ property: string;
98
+ nestedEntity: any;
99
+ hasId: boolean;
100
+ }>;
101
+ /**
102
+ * Find all entities that exist in the graph but are never referenced by other entities
103
+ * @param graph - The JSON-LD graph to analyze
104
+ * @returns Array of orphaned @id values
105
+ */
106
+ export declare function findOrphans(graph: JsonLdGraph): string[];
107
+ /**
108
+ * Inline all @id references within entities, replacing them with their full entity data
109
+ *
110
+ * This function takes an array of entities and recursively replaces all @id references
111
+ * with the actual entity data. If a specific root ID is provided, it returns only
112
+ * that entity with all its references inlined. Otherwise, it returns all entities
113
+ * with references inlined.
114
+ *
115
+ * @param entities - Array of JSON-LD entities
116
+ * @param rootId - Optional root entity @id to return (if not provided, returns all entities)
117
+ * @returns Either a single entity with inlined references or array of all entities with inlined references
118
+ */
119
+ export declare function inlineReferences(entities: JsonLdGraph, rootId?: string): JsonLdEntity | JsonLdGraph;
package/index.js ADDED
@@ -0,0 +1,404 @@
1
+ "use strict";
2
+ /**
3
+ * Custom JSON-LD graph utilities
4
+ *
5
+ * Simple, focused functions for working with JSON-LD graph arrays.
6
+ * No external dependencies, no context expansion - just pure graph traversal.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.findEntity = findEntity;
10
+ exports.findEntities = findEntities;
11
+ exports.findEntitiesByType = findEntitiesByType;
12
+ exports.extractReferences = extractReferences;
13
+ exports.extractSubgraph = extractSubgraph;
14
+ exports.extractSubgraphs = extractSubgraphs;
15
+ exports.findReferencingEntities = findReferencingEntities;
16
+ exports.extractSubgraphWithDepth = extractSubgraphWithDepth;
17
+ exports.findMissingReferences = findMissingReferences;
18
+ exports.findNestedEntities = findNestedEntities;
19
+ exports.findOrphans = findOrphans;
20
+ exports.inlineReferences = inlineReferences;
21
+ /**
22
+ * Find a single entity in the graph by @id
23
+ *
24
+ * @param graph - Array of JSON-LD entities
25
+ * @param id - The @id to search for
26
+ * @returns The entity if found, undefined otherwise
27
+ */
28
+ function findEntity(graph, id) {
29
+ return graph.find(entity => entity['@id'] === id);
30
+ }
31
+ /**
32
+ * Find multiple entities in the graph by @id
33
+ *
34
+ * @param graph - Array of JSON-LD entities
35
+ * @param ids - Array of @ids to search for
36
+ * @returns Array of found entities (may be fewer than requested if some not found)
37
+ */
38
+ function findEntities(graph, ids) {
39
+ const idSet = new Set(ids);
40
+ return graph.filter(entity => idSet.has(entity['@id']));
41
+ }
42
+ /**
43
+ * Find entities by @type
44
+ *
45
+ * @param graph - Array of JSON-LD entities
46
+ * @param type - The @type to search for
47
+ * @returns Array of entities matching the type
48
+ */
49
+ function findEntitiesByType(graph, type) {
50
+ return graph.filter(entity => {
51
+ const entityType = entity['@type'];
52
+ if (Array.isArray(entityType)) {
53
+ return entityType.includes(type);
54
+ }
55
+ return entityType === type;
56
+ });
57
+ }
58
+ /**
59
+ * Extract all @id references from an entity's properties
60
+ *
61
+ * @param entity - JSON-LD entity to scan
62
+ * @returns Set of @id strings found in the entity
63
+ */
64
+ function extractReferences(entity) {
65
+ const references = new Set();
66
+ function scanValue(value) {
67
+ if (value === null || value === undefined) {
68
+ return;
69
+ }
70
+ if (typeof value === 'string') {
71
+ // Check if it looks like an @id reference using regex pattern
72
+ // Pattern: ^(?:[a-zA-Z][a-zA-Z0-9+.-]*:)?[^\s]+$
73
+ // This matches:
74
+ // - URIs with scheme: scheme:path (e.g., mailto:user@example.com)
75
+ // - Compact URIs: prefix:suffix (e.g., person:danlynch, org:hyperweb)
76
+ // - Must not contain spaces (filters out titles/descriptions with colons)
77
+ const idPattern = /^(?:[a-zA-Z][a-zA-Z0-9+.-]*:)[^\s]+$/;
78
+ // Additional checks:
79
+ // - Must match the pattern
80
+ // - Must contain a colon (to be a reference)
81
+ // - Exclude http/https URLs (handled separately)
82
+ if (idPattern.test(value) && value.includes(':') && !value.startsWith('http')) {
83
+ references.add(value);
84
+ }
85
+ return;
86
+ }
87
+ if (Array.isArray(value)) {
88
+ value.forEach(scanValue);
89
+ return;
90
+ }
91
+ if (typeof value === 'object') {
92
+ // If it has an @id, add it
93
+ if (value['@id']) {
94
+ references.add(value['@id']);
95
+ }
96
+ // Recursively scan all properties
97
+ Object.values(value).forEach(scanValue);
98
+ return;
99
+ }
100
+ }
101
+ // Scan all properties except @id and @type
102
+ Object.entries(entity).forEach(([key, value]) => {
103
+ if (key !== '@id' && key !== '@type') {
104
+ scanValue(value);
105
+ }
106
+ });
107
+ return references;
108
+ }
109
+ /**
110
+ * Extract a subgraph containing an entity and all its referenced entities
111
+ *
112
+ * Recursively finds all @id references within the entity and includes
113
+ * those entities in the result. Returns a filtered array of the original
114
+ * graph elements - does not modify the entities themselves.
115
+ *
116
+ * @param graph - Array of JSON-LD entities
117
+ * @param id - The root @id to start from
118
+ * @returns Array containing the root entity and all recursively referenced entities
119
+ */
120
+ function extractSubgraph(graph, id) {
121
+ const result = new Map();
122
+ const visited = new Set();
123
+ const toProcess = new Set([id]);
124
+ while (toProcess.size > 0) {
125
+ const currentId = toProcess.values().next().value;
126
+ toProcess.delete(currentId);
127
+ if (visited.has(currentId)) {
128
+ continue;
129
+ }
130
+ visited.add(currentId);
131
+ const entity = findEntity(graph, currentId);
132
+ if (!entity) {
133
+ continue;
134
+ }
135
+ result.set(currentId, entity);
136
+ // Find all references in this entity
137
+ const references = extractReferences(entity);
138
+ // Add unvisited references to process queue
139
+ references.forEach(refId => {
140
+ if (!visited.has(refId)) {
141
+ toProcess.add(refId);
142
+ }
143
+ });
144
+ }
145
+ return Array.from(result.values());
146
+ }
147
+ /**
148
+ * Extract subgraphs for multiple root entities
149
+ *
150
+ * @param graph - Array of JSON-LD entities
151
+ * @param ids - Array of root @ids to start from
152
+ * @returns Array containing all entities and their recursively referenced entities
153
+ */
154
+ function extractSubgraphs(graph, ids) {
155
+ const allEntities = new Map();
156
+ ids.forEach(id => {
157
+ const subgraph = extractSubgraph(graph, id);
158
+ subgraph.forEach(entity => {
159
+ allEntities.set(entity['@id'], entity);
160
+ });
161
+ });
162
+ return Array.from(allEntities.values());
163
+ }
164
+ /**
165
+ * Find entities that reference a specific @id
166
+ *
167
+ * @param graph - Array of JSON-LD entities
168
+ * @param targetId - The @id to find references to
169
+ * @returns Array of entities that reference the target @id
170
+ */
171
+ function findReferencingEntities(graph, targetId) {
172
+ return graph.filter(entity => {
173
+ const references = extractReferences(entity);
174
+ return references.has(targetId);
175
+ });
176
+ }
177
+ /**
178
+ * Extract a subgraph with limited depth traversal
179
+ *
180
+ * Unlike extractSubgraph which recursively follows all references,
181
+ * this function only traverses to a specified depth from the root entity.
182
+ *
183
+ * @param graph - Array of JSON-LD entities
184
+ * @param id - The root @id to start from
185
+ * @param maxDepth - Maximum depth to traverse (1 = direct references only)
186
+ * @returns Array containing entities up to the specified depth
187
+ */
188
+ function extractSubgraphWithDepth(graph, id, maxDepth) {
189
+ if (maxDepth < 1) {
190
+ return [];
191
+ }
192
+ const result = new Map();
193
+ const visited = new Set();
194
+ const toProcess = [{ id, depth: 0 }];
195
+ while (toProcess.length > 0) {
196
+ const current = toProcess.shift();
197
+ if (visited.has(current.id) || current.depth > maxDepth) {
198
+ continue;
199
+ }
200
+ visited.add(current.id);
201
+ const entity = findEntity(graph, current.id);
202
+ if (!entity) {
203
+ continue;
204
+ }
205
+ result.set(current.id, entity);
206
+ // Only process references if we haven't reached max depth
207
+ if (current.depth < maxDepth) {
208
+ const references = extractReferences(entity);
209
+ references.forEach(refId => {
210
+ if (!visited.has(refId)) {
211
+ toProcess.push({ id: refId, depth: current.depth + 1 });
212
+ }
213
+ });
214
+ }
215
+ }
216
+ return Array.from(result.values());
217
+ }
218
+ /**
219
+ * Find all @id references that don't have corresponding entities in the graph
220
+ * @param graph - The JSON-LD graph to analyze
221
+ * @returns Array of missing @id references
222
+ */
223
+ function findMissingReferences(graph) {
224
+ // First, collect all entity @ids that exist in the graph
225
+ const existingIds = new Set();
226
+ for (const entity of graph) {
227
+ if (entity['@id']) {
228
+ existingIds.add(entity['@id']);
229
+ }
230
+ }
231
+ // Then, collect all referenced @ids
232
+ const allReferences = new Set();
233
+ for (const entity of graph) {
234
+ const references = extractReferences(entity);
235
+ for (const ref of references) {
236
+ allReferences.add(ref);
237
+ }
238
+ }
239
+ // Find references that don't exist
240
+ const missing = [];
241
+ for (const ref of allReferences) {
242
+ if (!existingIds.has(ref)) {
243
+ missing.push(ref);
244
+ }
245
+ }
246
+ return missing.sort(); // Sort for consistent output
247
+ }
248
+ /**
249
+ * Find entities that contain nested objects (potential normalization candidates)
250
+ * @param graph - The JSON-LD graph to analyze
251
+ * @returns Array of objects with parent @id and details about nested entities
252
+ */
253
+ function findNestedEntities(graph) {
254
+ const results = [];
255
+ function isNestedEntity(value) {
256
+ // Check if it's an object (not null, not array)
257
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
258
+ return false;
259
+ }
260
+ // Skip if it's just an @id reference (only has @id property)
261
+ if (Object.keys(value).length === 1 && value['@id']) {
262
+ return false;
263
+ }
264
+ // It's a nested entity if it has properties beyond just @id
265
+ return true;
266
+ }
267
+ function scanEntity(entity, parentId, basePath = '') {
268
+ for (const [key, value] of Object.entries(entity)) {
269
+ // Skip special JSON-LD properties
270
+ if (key.startsWith('@'))
271
+ continue;
272
+ const propertyPath = basePath ? `${basePath}.${key}` : key;
273
+ if (isNestedEntity(value)) {
274
+ results.push({
275
+ parentId: parentId,
276
+ property: propertyPath,
277
+ nestedEntity: value,
278
+ hasId: !!value['@id']
279
+ });
280
+ // Recursively scan the nested entity
281
+ scanEntity(value, parentId, propertyPath);
282
+ }
283
+ else if (Array.isArray(value)) {
284
+ // Check arrays for nested entities
285
+ value.forEach((item, index) => {
286
+ if (isNestedEntity(item)) {
287
+ const arrayPath = `${propertyPath}[${index}]`;
288
+ results.push({
289
+ parentId: parentId,
290
+ property: arrayPath,
291
+ nestedEntity: item,
292
+ hasId: !!item['@id']
293
+ });
294
+ // Recursively scan the nested entity in array
295
+ scanEntity(item, parentId, arrayPath);
296
+ }
297
+ });
298
+ }
299
+ }
300
+ }
301
+ for (const entity of graph) {
302
+ if (!entity['@id'])
303
+ continue;
304
+ scanEntity(entity, entity['@id']);
305
+ }
306
+ return results;
307
+ }
308
+ /**
309
+ * Find all entities that exist in the graph but are never referenced by other entities
310
+ * @param graph - The JSON-LD graph to analyze
311
+ * @returns Array of orphaned @id values
312
+ */
313
+ function findOrphans(graph) {
314
+ // First, collect all entity @ids that exist in the graph
315
+ const allIds = new Set();
316
+ for (const entity of graph) {
317
+ if (entity['@id']) {
318
+ allIds.add(entity['@id']);
319
+ }
320
+ }
321
+ // Then, collect all referenced @ids
322
+ const referencedIds = new Set();
323
+ for (const entity of graph) {
324
+ const references = extractReferences(entity);
325
+ for (const ref of references) {
326
+ referencedIds.add(ref);
327
+ }
328
+ }
329
+ // Find entities that exist but are never referenced
330
+ const orphans = [];
331
+ for (const id of allIds) {
332
+ if (!referencedIds.has(id)) {
333
+ orphans.push(id);
334
+ }
335
+ }
336
+ return orphans.sort(); // Sort for consistent output
337
+ }
338
+ /**
339
+ * Inline all @id references within entities, replacing them with their full entity data
340
+ *
341
+ * This function takes an array of entities and recursively replaces all @id references
342
+ * with the actual entity data. If a specific root ID is provided, it returns only
343
+ * that entity with all its references inlined. Otherwise, it returns all entities
344
+ * with references inlined.
345
+ *
346
+ * @param entities - Array of JSON-LD entities
347
+ * @param rootId - Optional root entity @id to return (if not provided, returns all entities)
348
+ * @returns Either a single entity with inlined references or array of all entities with inlined references
349
+ */
350
+ function inlineReferences(entities, rootId) {
351
+ // Create a lookup map for all entities
352
+ const entityMap = new Map();
353
+ entities.forEach(entity => {
354
+ if (entity['@id']) {
355
+ entityMap.set(entity['@id'], entity);
356
+ }
357
+ });
358
+ // Function to recursively inline references with circular reference protection
359
+ function inlineValue(value, visited = new Set()) {
360
+ if (value === null || value === undefined) {
361
+ return value;
362
+ }
363
+ if (Array.isArray(value)) {
364
+ return value.map(v => inlineValue(v, visited));
365
+ }
366
+ if (typeof value === 'object') {
367
+ // If it's an @id reference (object with only @id property), replace with the full entity
368
+ if (value['@id'] && Object.keys(value).length === 1) {
369
+ const id = value['@id'];
370
+ // Check for circular reference
371
+ if (visited.has(id)) {
372
+ // Return just the @id reference to break the cycle
373
+ return { '@id': id };
374
+ }
375
+ const referencedEntity = entityMap.get(id);
376
+ if (referencedEntity) {
377
+ // Add to visited set before processing
378
+ const newVisited = new Set(visited);
379
+ newVisited.add(id);
380
+ // Create a copy and inline its references
381
+ const copy = { ...referencedEntity };
382
+ return inlineValue(copy, newVisited);
383
+ }
384
+ }
385
+ // Otherwise, recursively process all properties
386
+ const result = {};
387
+ for (const [key, val] of Object.entries(value)) {
388
+ result[key] = inlineValue(val, visited);
389
+ }
390
+ return result;
391
+ }
392
+ return value;
393
+ }
394
+ // If a root ID is specified, return only that entity with inlined references
395
+ if (rootId) {
396
+ const mainEntity = entities.find(e => e['@id'] === rootId);
397
+ if (!mainEntity) {
398
+ throw new Error(`Entity with @id "${rootId}" not found`);
399
+ }
400
+ return inlineValue(mainEntity);
401
+ }
402
+ // Otherwise, inline references in all entities
403
+ return entities.map(entity => inlineValue(entity));
404
+ }
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "jsonldjs",
3
+ "version": "0.1.0",
4
+ "description": "JSON-LD Tooling",
5
+ "author": "Dan Lynch <pyramation@gmail.com>",
6
+ "homepage": "https://github.com/hyperweb-io/jsonldjs",
7
+ "license": "SEE LICENSE IN LICENSE",
8
+ "main": "index.js",
9
+ "module": "esm/index.js",
10
+ "types": "index.d.ts",
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "directory": "dist"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/hyperweb-io/jsonld-tools"
18
+ },
19
+ "keywords": [
20
+ "jsonld-tools"
21
+ ],
22
+ "bugs": {
23
+ "url": "https://github.com/hyperweb-io/jsonld-tools/issues"
24
+ },
25
+ "scripts": {
26
+ "copy": "copyfiles -f ../../LICENSE README.md package.json dist",
27
+ "clean": "rimraf dist",
28
+ "build": "pnpm run clean && tsc && tsc -p tsconfig.esm.json && pnpm run copy",
29
+ "build:dev": "pnpm run clean && tsc --declarationMap && tsc -p tsconfig.esm.json && pnpm run copy",
30
+ "test": "jest",
31
+ "test:watch": "jest --watch",
32
+ "test:debug": "node --inspect node_modules/.bin/jest --runInBand"
33
+ }
34
+ }