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/README.md CHANGED
@@ -1 +1,405 @@
1
- # jsonldjs
1
+ # `jsonldjs`
2
+
3
+ A powerful, generic JSON-LD builder with comprehensive entity and property filtering capabilities. Provides both immutable configuration building and mutable graph processing with a fluent interface.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ # Using pnpm (recommended)
9
+ pnpm add jsonldjs
10
+
11
+ # Using npm
12
+ npm install jsonldjs
13
+
14
+ # Using yarn
15
+ yarn add jsonldjs
16
+ ```
17
+
18
+ ## Features
19
+
20
+ - **Configuration-First Design**: Separate immutable configuration from graph processing for maximum flexibility
21
+ - **Fluent Interface**: Chainable methods for building complex filtering logic
22
+ - **Property-Level Filtering**: Filter properties by entity IDs or types
23
+ - **Subgraph Extraction**: Extract connected subgraphs with reference following
24
+ - **Runtime Overrides**: Apply configuration and then override at runtime
25
+ - **Type Safety**: Full TypeScript support with proper type inference
26
+ - **Extensibility**: Custom pipes and transformation functions
27
+
28
+ ## Quick Start
29
+
30
+ ### Basic Usage
31
+
32
+ ```typescript
33
+ import { createJsonLdBuilder } from 'jsonldjs';
34
+ import { jsonldGraph } from '@/data/jsonld';
35
+
36
+ // Simple filtering
37
+ const result = createJsonLdBuilder()
38
+ .baseGraph(jsonldGraph)
39
+ .includeTypes(['Organization', 'Person'])
40
+ .excludeTypes(['ImageObject'])
41
+ .maxEntities(10)
42
+ .build({
43
+ prettyPrint: true,
44
+ withScriptTag: true,
45
+ scriptId: 'json-ld',
46
+ });
47
+ ```
48
+
49
+ ### Configuration-First Approach
50
+
51
+ ```typescript
52
+ import { createJsonLdBuilder, createJsonLdConfig } from 'jsonldjs';
53
+
54
+ // Create reusable configurations
55
+ const globalConfig = createJsonLdConfig()
56
+ .baseGraph(jsonldGraph)
57
+ .includeIds(['org:hyperweb', 'website:hyperweb.io'])
58
+ .filterPropertiesByIds(['org:hyperweb'], { exclude: ['subjectOf'] });
59
+
60
+ // Extend configurations immutably
61
+ const homeConfig = globalConfig.excludeTypes(['ImageObject']);
62
+ const blogConfig = globalConfig.includeTypes(['Article']);
63
+
64
+ // Use configurations
65
+ const result = createJsonLdBuilder()
66
+ .mergeConfig(homeConfig.getConfig())
67
+ .excludeIds(['runtime:override']) // Runtime overrides
68
+ .build({ prettyPrint: true });
69
+ ```
70
+
71
+ ## Configuration Merging Behavior
72
+
73
+ ### Default Merging
74
+
75
+ All configuration methods **merge by default** instead of replacing. This provides predictable behavior across all methods:
76
+
77
+ ```typescript
78
+ const config = createJsonLdConfig()
79
+ .includeIds(['a', 'b'])
80
+ .includeIds(['c', 'd']) // Result: ['a', 'b', 'c', 'd']
81
+ .includeTypes(['Person'])
82
+ .includeTypes(['Organization']); // Result: ['Person', 'Organization']
83
+ ```
84
+
85
+ ### Clear Methods
86
+
87
+ When you need to replace instead of merge, use the clear methods:
88
+
89
+ ```typescript
90
+ const config = createJsonLdConfig()
91
+ .includeIds(['old1', 'old2'])
92
+ .clearIds() // Clear both includeIds and excludeIds
93
+ .includeIds(['new1', 'new2']); // Result: ['new1', 'new2']
94
+ ```
95
+
96
+ #### Available Clear Methods
97
+
98
+ - `clearIds()` - Clears both `includeIds` and `excludeIds`
99
+ - `clearTypes()` - Clears both `includeTypes` and `excludeTypes`
100
+ - `clearPropertyRequirements()` - Clears both `requiredProperties` and `excludeEntitiesWithProperties`
101
+ - `clearPropertyFilters()` - Clears both `propertyFiltersByIds` and `propertyFiltersByTypes`
102
+ - `clearSubgraph()` - Clears `subgraphRoots`
103
+ - `clearAll()` - Clears entire configuration (except `baseGraph`)
104
+
105
+ ## API Reference
106
+
107
+ ### Factory Functions
108
+
109
+ #### `createJsonLdConfig()`
110
+
111
+ Creates a new immutable configuration builder.
112
+
113
+ ```typescript
114
+ const config = createJsonLdConfig()
115
+ .baseGraph(graph)
116
+ .includeIds(['org:hyperweb'])
117
+ .excludeTypes(['ImageObject']);
118
+ ```
119
+
120
+ #### `createJsonLdBuilder()`
121
+
122
+ Creates a new builder that extends the configuration builder with graph processing capabilities.
123
+
124
+ ```typescript
125
+ const builder = createJsonLdBuilder().baseGraph(graph).mergeConfig(config);
126
+ ```
127
+
128
+ ### Configuration Methods
129
+
130
+ All methods are inherited by the builder from the configuration builder:
131
+
132
+ #### Entity Filtering
133
+
134
+ - `.includeIds(ids: string[])` - Include entities with these IDs (merges with existing)
135
+ - `.excludeIds(ids: string[])` - Exclude entities with these IDs (merges with existing)
136
+ - `.includeTypes(types: string[])` - Include these entity types (merges with existing)
137
+ - `.excludeTypes(types: string[])` - Exclude these entity types (merges with existing)
138
+ - `.customFilter(fn: JsonLdFilter)` - Apply custom filter function
139
+ - `.maxEntities(max: number)` - Limit maximum number of entities
140
+ - `.requiredProperties(props: string[])` - Include entities with these properties (merges with existing)
141
+ - `.excludeEntitiesWithProperties(props: string[])` - Exclude entities with these properties (merges with existing)
142
+
143
+ #### Clear Methods
144
+
145
+ - `.clearIds()` - Clear both includeIds and excludeIds
146
+ - `.clearTypes()` - Clear both includeTypes and excludeTypes
147
+ - `.clearPropertyRequirements()` - Clear both requiredProperties and excludeEntitiesWithProperties
148
+ - `.clearPropertyFilters()` - Clear both propertyFiltersByIds and propertyFiltersByTypes
149
+ - `.clearSubgraph()` - Clear subgraphRoots
150
+ - `.clearAll()` - Clear entire configuration (except baseGraph)
151
+
152
+ #### Configuration Merging
153
+
154
+ - `.mergeConfig(config: JsonLdConfig)` - Merge with another complete configuration
155
+ - `.mergeFilters(filters: JsonLdFilterOptions)` - Merge only the filters part of another configuration
156
+
157
+ **Available in both config builder and main builder** - These methods work the same way in both classes.
158
+
159
+ ```typescript
160
+ // Config builder usage
161
+ const baseConfig = createJsonLdConfig().includeTypes(['Person']);
162
+ const otherConfig = createJsonLdConfig()
163
+ .includeTypes(['Organization'])
164
+ .excludeIds(['test'])
165
+ .getConfig();
166
+ const merged = baseConfig.mergeConfig(otherConfig);
167
+ // Result: includeTypes: ['Person', 'Organization'], excludeIds: ['test']
168
+
169
+ // Main builder usage (processes graph immediately)
170
+ const result = createJsonLdBuilder()
171
+ .baseGraph(graph)
172
+ .includeTypes(['Person'])
173
+ .mergeConfig(otherConfig)
174
+ .build({ prettyPrint: true });
175
+
176
+ // Merge only filters
177
+ const baseConfig = createJsonLdConfig().includeTypes(['Person']).addEntities([entity]);
178
+ const otherFilters = { includeTypes: ['Organization'], maxEntities: 10 };
179
+ const merged = baseConfig.mergeFilters(otherFilters);
180
+ // Result: includeTypes: ['Person', 'Organization'], maxEntities: 10, additionalEntities preserved
181
+ ```
182
+
183
+ #### Property Filtering
184
+
185
+ - `.filterPropertiesByIds(entityIds, rule)` - Filter properties for specific entity IDs
186
+ - `.filterPropertiesByTypes(entityTypes, rule)` - Filter properties for specific entity types
187
+
188
+ ```typescript
189
+ // Filter properties by entity ID
190
+ .filterPropertiesByIds(['org:hyperweb'], {
191
+ exclude: ['subjectOf', 'member']
192
+ })
193
+
194
+ // Filter properties by entity type
195
+ .filterPropertiesByTypes(['Article'], {
196
+ include: ['headline', 'author', 'datePublished']
197
+ })
198
+ ```
199
+
200
+ #### Graph Operations
201
+
202
+ - `.baseGraph(graph: JsonLdGraph)` - Set the base graph to process
203
+ - `.subgraph(rootIds: string[])` - Extract subgraph starting from these root IDs
204
+ - `.addEntities(entities: JsonLdEntity[])` - Add additional entities
205
+ - `.pipe(fn: PipeFunction)` - Add custom transformation function
206
+
207
+ #### Builder-Only Methods
208
+
209
+ - `.getCurrentGraph()` - Get the current graph state
210
+ - `.build(options?: BuildOptions)` - Build the final JSON-LD output
211
+
212
+ ### Build Options
213
+
214
+ ```typescript
215
+ interface BuildOptions {
216
+ prettyPrint?: boolean; // Pretty-print JSON output (default: true)
217
+ contextUrl?: string; // Custom context URL (default: 'https://schema.org')
218
+ withScriptTag?: boolean; // Wrap in script tag (default: false)
219
+ scriptId?: string; // Script tag ID
220
+ }
221
+ ```
222
+
223
+ ## Advanced Usage
224
+
225
+ ### Complex Filtering Logic
226
+
227
+ The builder implements three distinct filtering paths based on configuration:
228
+
229
+ 1. **Subgraph Mode**: When `subgraph()` is used, property filtering is applied during traversal
230
+ 2. **IncludeIds Mode**: When `includeIds()` is used, entities are filtered first, then additional filters applied
231
+ 3. **Global Mode**: Property filtering is applied first, then entity filtering
232
+
233
+ ```typescript
234
+ // Subgraph mode - follows references with property filtering
235
+ const result = createJsonLdBuilder()
236
+ .baseGraph(graph)
237
+ .subgraph(['org:hyperweb'])
238
+ .filterPropertiesByIds(['org:hyperweb'], { exclude: ['subjectOf'] })
239
+ .build();
240
+
241
+ // IncludeIds mode - simple entity filtering
242
+ const result = createJsonLdBuilder()
243
+ .baseGraph(graph)
244
+ .includeIds(['org:hyperweb', 'person:john'])
245
+ .excludeTypes(['ImageObject'])
246
+ .build();
247
+ ```
248
+
249
+ ### Custom Transformations
250
+
251
+ ```typescript
252
+ const result = createJsonLdBuilder()
253
+ .baseGraph(graph)
254
+ .includeTypes(['Person'])
255
+ .pipe((graph) =>
256
+ graph.map((entity) => ({
257
+ ...entity,
258
+ processed: true,
259
+ }))
260
+ )
261
+ .pipe((graph) => graph.filter((entity) => entity.name))
262
+ .build();
263
+ ```
264
+
265
+ ### Configuration Reuse
266
+
267
+ ```typescript
268
+ // Base configuration
269
+ const baseConfig = createJsonLdConfig()
270
+ .baseGraph(jsonldGraph)
271
+ .filterPropertiesByIds(['org:hyperweb'], { exclude: ['subjectOf'] });
272
+
273
+ // Page-specific configurations
274
+ const homeConfig = baseConfig.excludeTypes(['ImageObject']);
275
+ const blogConfig = baseConfig.includeTypes(['Article']);
276
+ const personConfig = baseConfig.includeTypes(['Person', 'Organization']);
277
+
278
+ // Use with different base graphs
279
+ const articlesConfig = baseConfig.baseGraph(articlesGraph);
280
+ ```
281
+
282
+ ## Options Processing Order
283
+
284
+ The JSON-LD builder processes options in a specific order defined by the `processGraph` method. Understanding this order is crucial for predicting the final output when multiple filtering options are applied.
285
+
286
+ ### Processing Layers
287
+
288
+ The builder processes options in the following sequential layers:
289
+
290
+ #### 1. **Configuration Validation**
291
+
292
+ - Validates that a base graph is provided
293
+ - Checks for critical configuration errors that would break processing
294
+ - Throws errors if validation fails
295
+
296
+ #### 2. **Subgraph Extraction** (Layer 1)
297
+
298
+ - **Condition**: Only when `subgraphRoots` are configured via `.subgraph(rootIds)`
299
+ - **Process**: Extracts connected subgraphs starting from root entities
300
+ - **Property Filtering**: Applied **during** subgraph traversal for optimal performance
301
+ - **Result**: Property filters are marked as applied to avoid duplicate processing
302
+
303
+ ```typescript
304
+ // Example: Subgraph extraction with property filtering
305
+ const result = createJsonLdBuilder()
306
+ .baseGraph(graph)
307
+ .subgraph(['org:hyperweb']) // Layer 1: Extract subgraph
308
+ .filterPropertiesByIds(['org:hyperweb'], { exclude: ['subjectOf'] }) // Applied during traversal
309
+ .build();
310
+ ```
311
+
312
+ #### 3. **Entity and Property Filtering** (Layer 2)
313
+
314
+ - **Condition**: When entity filters are configured (includeIds, excludeIds, includeTypes, etc.)
315
+ - **Sub-step 3a - Property Filtering**: Applied first if not already done in Layer 1
316
+ - Filters properties based on entity IDs or types
317
+ - Uses `filterGraphProperties()` function
318
+ - **Sub-step 3b - Entity Filtering**: Applied after property filtering
319
+ - Filters entire entities based on ID, type, and other criteria
320
+ - Uses `filterJsonLdGraph()` function
321
+
322
+ ```typescript
323
+ // Example: Property filtering followed by entity filtering
324
+ const result = createJsonLdBuilder()
325
+ .baseGraph(graph)
326
+ .filterPropertiesByTypes(['Article'], { include: ['headline', 'author'] }) // 3a: Property filtering
327
+ .includeTypes(['Article', 'Person']) // 3b: Entity filtering
328
+ .excludeIds(['unwanted:id']) // 3b: Additional entity filtering
329
+ .build();
330
+ ```
331
+
332
+ #### 4. **Entity Population**
333
+
334
+ - **Condition**: When `populateConfig` is set
335
+ - **Process**: Applies population rules to add related entities
336
+ - **Function**: Uses `applyPopulateConfig()`
337
+
338
+ #### 5. **Additional Entities**
339
+
340
+ - **Condition**: When additional entities are specified via `.addEntities()`
341
+ - **Process**: Appends additional entities to the graph
342
+ - **Note**: These entities bypass all previous filtering
343
+
344
+ #### 6. **Custom Transformation Pipes**
345
+
346
+ - **Condition**: When custom pipes are added via `.pipe(fn)`
347
+ - **Process**: Applies custom transformation functions in the order they were added
348
+ - **Note**: This is the final processing step before output
349
+
350
+ ```typescript
351
+ // Example: Custom pipes applied last
352
+ const result = createJsonLdBuilder()
353
+ .baseGraph(graph)
354
+ .includeTypes(['Person'])
355
+ .pipe((graph) => graph.map((entity) => ({ ...entity, processed: true }))) // Applied last
356
+ .pipe((graph) => graph.filter((entity) => entity.name)) // Applied after previous pipe
357
+ .build();
358
+ ```
359
+
360
+ ### Key Processing Rules
361
+
362
+ 1. **Property Filters Before Entity Filters**: Property filtering always happens before entity filtering (except in subgraph mode where they're combined)
363
+
364
+ 2. **Subgraph Mode Optimization**: When using subgraphs, property filtering is applied during traversal for better performance
365
+
366
+ 3. **Single Property Filter Application**: Property filters are only applied once to avoid duplicate processing
367
+
368
+ 4. **Additive Additional Entities**: Entities added via `.addEntities()` are appended after all filtering
369
+
370
+ 5. **Sequential Pipe Execution**: Custom pipes are executed in the order they were added
371
+
372
+ ## Performance Considerations
373
+
374
+ - **Immutable Configurations**: Each configuration method returns a new object, enabling safe reuse
375
+ - **Lazy Evaluation**: Graph processing only occurs when `build()` or `getCurrentGraph()` is called
376
+ - **Efficient Filtering**: Uses optimized filtering paths based on configuration type
377
+ - **Memory Management**: Avoids unnecessary intermediate copies of large graphs
378
+
379
+ ## Development
380
+
381
+ ### Prerequisites
382
+
383
+ - Node.js 16+
384
+ - pnpm (recommended package manager)
385
+
386
+ ### Setup
387
+
388
+ 1. Clone the repository:
389
+
390
+ ```bash
391
+ git clone https://github.com/hyperweb-io/jsonld-tools.git
392
+ cd jsonld-tools
393
+ ```
394
+
395
+ 2. Install dependencies:
396
+
397
+ ```bash
398
+ pnpm install
399
+ ```
400
+
401
+ 3. Build the project:
402
+
403
+ ```bash
404
+ pnpm run build
405
+ ```
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Utility functions for JSON-LD builder
3
+ *
4
+ * Provides configuration merging, validation, and transformation utilities
5
+ * for the JSON-LD builder system.
6
+ */
7
+ import type { JsonLdEntity, JsonLdGraph, PropertyFilterConfig, PropertyFilterRule } from './jsonld-utils';
8
+ import type { JsonLdConfig, JsonLdFilterOptions, PopulateConfig, PropertyFilterByIdRule, PropertyFilterByTypeRule } from './types';
9
+ /**
10
+ * Merge two configurations, with the second taking precedence
11
+ */
12
+ export declare function mergeConfigs(base: JsonLdConfig, override: JsonLdConfig): JsonLdConfig;
13
+ /**
14
+ * Merge filter options, merging arrays and using override for single values
15
+ */
16
+ export declare function mergeFilterOptions(base?: JsonLdFilterOptions, override?: JsonLdFilterOptions): JsonLdFilterOptions | undefined;
17
+ /**
18
+ * Convert property filter by ID rules to PropertyFilterConfig
19
+ */
20
+ export declare function convertPropertyFiltersByIds(rules: PropertyFilterByIdRule[]): PropertyFilterRule[];
21
+ /**
22
+ * Convert property filter by type rules to PropertyFilterConfig
23
+ */
24
+ export declare function convertPropertyFiltersByTypes(rules: PropertyFilterByTypeRule[]): PropertyFilterRule[];
25
+ /**
26
+ * Build complete property filter configuration from all sources
27
+ */
28
+ export declare function buildPropertyFilterConfig(config: JsonLdConfig): PropertyFilterConfig | undefined;
29
+ /**
30
+ * Validate configuration for common issues
31
+ */
32
+ export declare function validateConfig(config: JsonLdConfig): string[];
33
+ /**
34
+ * Apply populate configuration to entities in the graph
35
+ */
36
+ export declare function applyPopulateConfig(graph: JsonLdGraph, populateConfig: PopulateConfig): JsonLdGraph;
37
+ /**
38
+ * Validate runtime configuration for critical errors only
39
+ * This is more lenient than the general validateConfig to handle runtime overrides
40
+ */
41
+ export declare function validateRuntimeConfig(config: JsonLdConfig): string[];
42
+ /**
43
+ * Type guard to check if an entity matches a type
44
+ */
45
+ export declare function entityHasType(entity: JsonLdEntity, type: string): boolean;
46
+ /**
47
+ * Type guard to check if an entity has any of the specified types
48
+ */
49
+ export declare function entityHasAnyType(entity: JsonLdEntity, types: string[]): boolean;
50
+ /**
51
+ * Get all types from an entity as an array
52
+ */
53
+ export declare function getEntityTypes(entity: JsonLdEntity): string[];
54
+ /**
55
+ * Apply filters to a JSON-LD graph (copied from head-manager/filters.ts for self-containment)
56
+ */
57
+ export declare function filterJsonLdGraph(graph: JsonLdGraph, options: JsonLdFilterOptions): JsonLdGraph;