jsonldjs 0.1.0 → 0.1.1
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 +375 -1
- package/builder-utils.d.ts +53 -0
- package/builder-utils.js +272 -0
- package/builder.d.ts +48 -0
- package/builder.js +127 -0
- package/config.d.ts +133 -0
- package/config.js +306 -0
- package/esm/builder-utils.js +259 -0
- package/esm/builder.js +122 -0
- package/esm/config.js +301 -0
- package/esm/index.js +4 -390
- package/esm/jsonld-utils.js +483 -0
- package/esm/types.js +8 -0
- package/index.d.ts +5 -119
- package/index.js +24 -402
- package/jsonld-utils.d.ts +142 -0
- package/jsonld-utils.js +500 -0
- package/package.json +1 -1
- package/types.d.ts +158 -0
- package/types.js +9 -0
package/README.md
CHANGED
|
@@ -1 +1,375 @@
|
|
|
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
|
+
.applyConfig(homeConfig)
|
|
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).applyConfig(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
|
+
#### Property Filtering
|
|
153
|
+
|
|
154
|
+
- `.filterPropertiesByIds(entityIds, rule)` - Filter properties for specific entity IDs
|
|
155
|
+
- `.filterPropertiesByTypes(entityTypes, rule)` - Filter properties for specific entity types
|
|
156
|
+
|
|
157
|
+
```typescript
|
|
158
|
+
// Filter properties by entity ID
|
|
159
|
+
.filterPropertiesByIds(['org:hyperweb'], {
|
|
160
|
+
exclude: ['subjectOf', 'member']
|
|
161
|
+
})
|
|
162
|
+
|
|
163
|
+
// Filter properties by entity type
|
|
164
|
+
.filterPropertiesByTypes(['Article'], {
|
|
165
|
+
include: ['headline', 'author', 'datePublished']
|
|
166
|
+
})
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
#### Graph Operations
|
|
170
|
+
|
|
171
|
+
- `.baseGraph(graph: JsonLdGraph)` - Set the base graph to process
|
|
172
|
+
- `.subgraph(rootIds: string[])` - Extract subgraph starting from these root IDs
|
|
173
|
+
- `.addEntities(entities: JsonLdEntity[])` - Add additional entities
|
|
174
|
+
- `.pipe(fn: PipeFunction)` - Add custom transformation function
|
|
175
|
+
|
|
176
|
+
#### Builder-Only Methods
|
|
177
|
+
|
|
178
|
+
- `.applyConfig(config: JsonLdConfig)` - Apply a pre-built configuration
|
|
179
|
+
- `.getCurrentGraph()` - Get the current graph state
|
|
180
|
+
- `.build(options?: BuildOptions)` - Build the final JSON-LD output
|
|
181
|
+
|
|
182
|
+
### Build Options
|
|
183
|
+
|
|
184
|
+
```typescript
|
|
185
|
+
interface BuildOptions {
|
|
186
|
+
prettyPrint?: boolean; // Pretty-print JSON output (default: true)
|
|
187
|
+
contextUrl?: string; // Custom context URL (default: 'https://schema.org')
|
|
188
|
+
withScriptTag?: boolean; // Wrap in script tag (default: false)
|
|
189
|
+
scriptId?: string; // Script tag ID
|
|
190
|
+
}
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
## Advanced Usage
|
|
194
|
+
|
|
195
|
+
### Complex Filtering Logic
|
|
196
|
+
|
|
197
|
+
The builder implements three distinct filtering paths based on configuration:
|
|
198
|
+
|
|
199
|
+
1. **Subgraph Mode**: When `subgraph()` is used, property filtering is applied during traversal
|
|
200
|
+
2. **IncludeIds Mode**: When `includeIds()` is used, entities are filtered first, then additional filters applied
|
|
201
|
+
3. **Global Mode**: Property filtering is applied first, then entity filtering
|
|
202
|
+
|
|
203
|
+
```typescript
|
|
204
|
+
// Subgraph mode - follows references with property filtering
|
|
205
|
+
const result = createJsonLdBuilder()
|
|
206
|
+
.baseGraph(graph)
|
|
207
|
+
.subgraph(['org:hyperweb'])
|
|
208
|
+
.filterPropertiesByIds(['org:hyperweb'], { exclude: ['subjectOf'] })
|
|
209
|
+
.build();
|
|
210
|
+
|
|
211
|
+
// IncludeIds mode - simple entity filtering
|
|
212
|
+
const result = createJsonLdBuilder()
|
|
213
|
+
.baseGraph(graph)
|
|
214
|
+
.includeIds(['org:hyperweb', 'person:john'])
|
|
215
|
+
.excludeTypes(['ImageObject'])
|
|
216
|
+
.build();
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
### Custom Transformations
|
|
220
|
+
|
|
221
|
+
```typescript
|
|
222
|
+
const result = createJsonLdBuilder()
|
|
223
|
+
.baseGraph(graph)
|
|
224
|
+
.includeTypes(['Person'])
|
|
225
|
+
.pipe((graph) =>
|
|
226
|
+
graph.map((entity) => ({
|
|
227
|
+
...entity,
|
|
228
|
+
processed: true,
|
|
229
|
+
}))
|
|
230
|
+
)
|
|
231
|
+
.pipe((graph) => graph.filter((entity) => entity.name))
|
|
232
|
+
.build();
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
### Configuration Reuse
|
|
236
|
+
|
|
237
|
+
```typescript
|
|
238
|
+
// Base configuration
|
|
239
|
+
const baseConfig = createJsonLdConfig()
|
|
240
|
+
.baseGraph(jsonldGraph)
|
|
241
|
+
.filterPropertiesByIds(['org:hyperweb'], { exclude: ['subjectOf'] });
|
|
242
|
+
|
|
243
|
+
// Page-specific configurations
|
|
244
|
+
const homeConfig = baseConfig.excludeTypes(['ImageObject']);
|
|
245
|
+
const blogConfig = baseConfig.includeTypes(['Article']);
|
|
246
|
+
const personConfig = baseConfig.includeTypes(['Person', 'Organization']);
|
|
247
|
+
|
|
248
|
+
// Use with different base graphs
|
|
249
|
+
const articlesConfig = baseConfig.baseGraph(articlesGraph);
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
## Options Processing Order
|
|
253
|
+
|
|
254
|
+
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.
|
|
255
|
+
|
|
256
|
+
### Processing Layers
|
|
257
|
+
|
|
258
|
+
The builder processes options in the following sequential layers:
|
|
259
|
+
|
|
260
|
+
#### 1. **Configuration Validation**
|
|
261
|
+
|
|
262
|
+
- Validates that a base graph is provided
|
|
263
|
+
- Checks for critical configuration errors that would break processing
|
|
264
|
+
- Throws errors if validation fails
|
|
265
|
+
|
|
266
|
+
#### 2. **Subgraph Extraction** (Layer 1)
|
|
267
|
+
|
|
268
|
+
- **Condition**: Only when `subgraphRoots` are configured via `.subgraph(rootIds)`
|
|
269
|
+
- **Process**: Extracts connected subgraphs starting from root entities
|
|
270
|
+
- **Property Filtering**: Applied **during** subgraph traversal for optimal performance
|
|
271
|
+
- **Result**: Property filters are marked as applied to avoid duplicate processing
|
|
272
|
+
|
|
273
|
+
```typescript
|
|
274
|
+
// Example: Subgraph extraction with property filtering
|
|
275
|
+
const result = createJsonLdBuilder()
|
|
276
|
+
.baseGraph(graph)
|
|
277
|
+
.subgraph(['org:hyperweb']) // Layer 1: Extract subgraph
|
|
278
|
+
.filterPropertiesByIds(['org:hyperweb'], { exclude: ['subjectOf'] }) // Applied during traversal
|
|
279
|
+
.build();
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
#### 3. **Entity and Property Filtering** (Layer 2)
|
|
283
|
+
|
|
284
|
+
- **Condition**: When entity filters are configured (includeIds, excludeIds, includeTypes, etc.)
|
|
285
|
+
- **Sub-step 3a - Property Filtering**: Applied first if not already done in Layer 1
|
|
286
|
+
- Filters properties based on entity IDs or types
|
|
287
|
+
- Uses `filterGraphProperties()` function
|
|
288
|
+
- **Sub-step 3b - Entity Filtering**: Applied after property filtering
|
|
289
|
+
- Filters entire entities based on ID, type, and other criteria
|
|
290
|
+
- Uses `filterJsonLdGraph()` function
|
|
291
|
+
|
|
292
|
+
```typescript
|
|
293
|
+
// Example: Property filtering followed by entity filtering
|
|
294
|
+
const result = createJsonLdBuilder()
|
|
295
|
+
.baseGraph(graph)
|
|
296
|
+
.filterPropertiesByTypes(['Article'], { include: ['headline', 'author'] }) // 3a: Property filtering
|
|
297
|
+
.includeTypes(['Article', 'Person']) // 3b: Entity filtering
|
|
298
|
+
.excludeIds(['unwanted:id']) // 3b: Additional entity filtering
|
|
299
|
+
.build();
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
#### 4. **Entity Population**
|
|
303
|
+
|
|
304
|
+
- **Condition**: When `populateConfig` is set
|
|
305
|
+
- **Process**: Applies population rules to add related entities
|
|
306
|
+
- **Function**: Uses `applyPopulateConfig()`
|
|
307
|
+
|
|
308
|
+
#### 5. **Additional Entities**
|
|
309
|
+
|
|
310
|
+
- **Condition**: When additional entities are specified via `.addEntities()`
|
|
311
|
+
- **Process**: Appends additional entities to the graph
|
|
312
|
+
- **Note**: These entities bypass all previous filtering
|
|
313
|
+
|
|
314
|
+
#### 6. **Custom Transformation Pipes**
|
|
315
|
+
|
|
316
|
+
- **Condition**: When custom pipes are added via `.pipe(fn)`
|
|
317
|
+
- **Process**: Applies custom transformation functions in the order they were added
|
|
318
|
+
- **Note**: This is the final processing step before output
|
|
319
|
+
|
|
320
|
+
```typescript
|
|
321
|
+
// Example: Custom pipes applied last
|
|
322
|
+
const result = createJsonLdBuilder()
|
|
323
|
+
.baseGraph(graph)
|
|
324
|
+
.includeTypes(['Person'])
|
|
325
|
+
.pipe((graph) => graph.map((entity) => ({ ...entity, processed: true }))) // Applied last
|
|
326
|
+
.pipe((graph) => graph.filter((entity) => entity.name)) // Applied after previous pipe
|
|
327
|
+
.build();
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
### Key Processing Rules
|
|
331
|
+
|
|
332
|
+
1. **Property Filters Before Entity Filters**: Property filtering always happens before entity filtering (except in subgraph mode where they're combined)
|
|
333
|
+
|
|
334
|
+
2. **Subgraph Mode Optimization**: When using subgraphs, property filtering is applied during traversal for better performance
|
|
335
|
+
|
|
336
|
+
3. **Single Property Filter Application**: Property filters are only applied once to avoid duplicate processing
|
|
337
|
+
|
|
338
|
+
4. **Additive Additional Entities**: Entities added via `.addEntities()` are appended after all filtering
|
|
339
|
+
|
|
340
|
+
5. **Sequential Pipe Execution**: Custom pipes are executed in the order they were added
|
|
341
|
+
|
|
342
|
+
## Performance Considerations
|
|
343
|
+
|
|
344
|
+
- **Immutable Configurations**: Each configuration method returns a new object, enabling safe reuse
|
|
345
|
+
- **Lazy Evaluation**: Graph processing only occurs when `build()` or `getCurrentGraph()` is called
|
|
346
|
+
- **Efficient Filtering**: Uses optimized filtering paths based on configuration type
|
|
347
|
+
- **Memory Management**: Avoids unnecessary intermediate copies of large graphs
|
|
348
|
+
|
|
349
|
+
## Development
|
|
350
|
+
|
|
351
|
+
### Prerequisites
|
|
352
|
+
|
|
353
|
+
- Node.js 16+
|
|
354
|
+
- pnpm (recommended package manager)
|
|
355
|
+
|
|
356
|
+
### Setup
|
|
357
|
+
|
|
358
|
+
1. Clone the repository:
|
|
359
|
+
|
|
360
|
+
```bash
|
|
361
|
+
git clone https://github.com/hyperweb-io/jsonld-tools.git
|
|
362
|
+
cd jsonld-tools
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
2. Install dependencies:
|
|
366
|
+
|
|
367
|
+
```bash
|
|
368
|
+
pnpm install
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
3. Build the project:
|
|
372
|
+
|
|
373
|
+
```bash
|
|
374
|
+
pnpm run build
|
|
375
|
+
```
|
|
@@ -0,0 +1,53 @@
|
|
|
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
|
+
* Convert property filter by ID rules to PropertyFilterConfig
|
|
15
|
+
*/
|
|
16
|
+
export declare function convertPropertyFiltersByIds(rules: PropertyFilterByIdRule[]): PropertyFilterRule[];
|
|
17
|
+
/**
|
|
18
|
+
* Convert property filter by type rules to PropertyFilterConfig
|
|
19
|
+
*/
|
|
20
|
+
export declare function convertPropertyFiltersByTypes(rules: PropertyFilterByTypeRule[]): PropertyFilterRule[];
|
|
21
|
+
/**
|
|
22
|
+
* Build complete property filter configuration from all sources
|
|
23
|
+
*/
|
|
24
|
+
export declare function buildPropertyFilterConfig(config: JsonLdConfig): PropertyFilterConfig | undefined;
|
|
25
|
+
/**
|
|
26
|
+
* Validate configuration for common issues
|
|
27
|
+
*/
|
|
28
|
+
export declare function validateConfig(config: JsonLdConfig): string[];
|
|
29
|
+
/**
|
|
30
|
+
* Apply populate configuration to entities in the graph
|
|
31
|
+
*/
|
|
32
|
+
export declare function applyPopulateConfig(graph: JsonLdGraph, populateConfig: PopulateConfig): JsonLdGraph;
|
|
33
|
+
/**
|
|
34
|
+
* Validate runtime configuration for critical errors only
|
|
35
|
+
* This is more lenient than the general validateConfig to handle runtime overrides
|
|
36
|
+
*/
|
|
37
|
+
export declare function validateRuntimeConfig(config: JsonLdConfig): string[];
|
|
38
|
+
/**
|
|
39
|
+
* Type guard to check if an entity matches a type
|
|
40
|
+
*/
|
|
41
|
+
export declare function entityHasType(entity: JsonLdEntity, type: string): boolean;
|
|
42
|
+
/**
|
|
43
|
+
* Type guard to check if an entity has any of the specified types
|
|
44
|
+
*/
|
|
45
|
+
export declare function entityHasAnyType(entity: JsonLdEntity, types: string[]): boolean;
|
|
46
|
+
/**
|
|
47
|
+
* Get all types from an entity as an array
|
|
48
|
+
*/
|
|
49
|
+
export declare function getEntityTypes(entity: JsonLdEntity): string[];
|
|
50
|
+
/**
|
|
51
|
+
* Apply filters to a JSON-LD graph (copied from head-manager/filters.ts for self-containment)
|
|
52
|
+
*/
|
|
53
|
+
export declare function filterJsonLdGraph(graph: JsonLdGraph, options: JsonLdFilterOptions): JsonLdGraph;
|
package/builder-utils.js
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Utility functions for JSON-LD builder
|
|
4
|
+
*
|
|
5
|
+
* Provides configuration merging, validation, and transformation utilities
|
|
6
|
+
* for the JSON-LD builder system.
|
|
7
|
+
*/
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.mergeConfigs = mergeConfigs;
|
|
10
|
+
exports.convertPropertyFiltersByIds = convertPropertyFiltersByIds;
|
|
11
|
+
exports.convertPropertyFiltersByTypes = convertPropertyFiltersByTypes;
|
|
12
|
+
exports.buildPropertyFilterConfig = buildPropertyFilterConfig;
|
|
13
|
+
exports.validateConfig = validateConfig;
|
|
14
|
+
exports.applyPopulateConfig = applyPopulateConfig;
|
|
15
|
+
exports.validateRuntimeConfig = validateRuntimeConfig;
|
|
16
|
+
exports.entityHasType = entityHasType;
|
|
17
|
+
exports.entityHasAnyType = entityHasAnyType;
|
|
18
|
+
exports.getEntityTypes = getEntityTypes;
|
|
19
|
+
exports.filterJsonLdGraph = filterJsonLdGraph;
|
|
20
|
+
/**
|
|
21
|
+
* Merge two configurations, with the second taking precedence
|
|
22
|
+
*/
|
|
23
|
+
function mergeConfigs(base, override) {
|
|
24
|
+
return {
|
|
25
|
+
// Base graph: override takes precedence
|
|
26
|
+
baseGraph: override.baseGraph ?? base.baseGraph,
|
|
27
|
+
// Filters: merge filter options
|
|
28
|
+
filters: mergeFilterOptions(base.filters, override.filters),
|
|
29
|
+
// Subgraph roots: override takes precedence
|
|
30
|
+
subgraphRoots: override.subgraphRoots ?? base.subgraphRoots,
|
|
31
|
+
// Property filters: combine arrays
|
|
32
|
+
propertyFilters: combinePropertyFilters(base.propertyFilters, override.propertyFilters),
|
|
33
|
+
// Property filters by IDs: combine arrays
|
|
34
|
+
propertyFiltersByIds: combineArrays(base.propertyFiltersByIds, override.propertyFiltersByIds),
|
|
35
|
+
// Property filters by types: combine arrays
|
|
36
|
+
propertyFiltersByTypes: combineArrays(base.propertyFiltersByTypes, override.propertyFiltersByTypes),
|
|
37
|
+
// Additional entities: combine arrays
|
|
38
|
+
additionalEntities: combineArrays(base.additionalEntities, override.additionalEntities),
|
|
39
|
+
// Pipes: combine arrays
|
|
40
|
+
pipes: combineArrays(base.pipes, override.pipes),
|
|
41
|
+
// Populate config: override takes precedence
|
|
42
|
+
populateConfig: override.populateConfig ?? base.populateConfig,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Merge filter options, merging arrays and using override for single values
|
|
47
|
+
*/
|
|
48
|
+
function mergeFilterOptions(base, override) {
|
|
49
|
+
if (!base && !override)
|
|
50
|
+
return undefined;
|
|
51
|
+
if (!base)
|
|
52
|
+
return override;
|
|
53
|
+
if (!override)
|
|
54
|
+
return base;
|
|
55
|
+
return {
|
|
56
|
+
// Merge arrays instead of replacing
|
|
57
|
+
includeTypes: combineArrays(base.includeTypes, override.includeTypes),
|
|
58
|
+
excludeTypes: combineArrays(base.excludeTypes, override.excludeTypes),
|
|
59
|
+
includeIds: combineArrays(base.includeIds, override.includeIds),
|
|
60
|
+
excludeIds: combineArrays(base.excludeIds, override.excludeIds),
|
|
61
|
+
requiredProperties: combineArrays(base.requiredProperties, override.requiredProperties),
|
|
62
|
+
excludeEntitiesWithProperties: combineArrays(base.excludeEntitiesWithProperties, override.excludeEntitiesWithProperties),
|
|
63
|
+
// Single values - override takes precedence
|
|
64
|
+
customFilter: override.customFilter ?? base.customFilter,
|
|
65
|
+
maxEntities: override.maxEntities ?? base.maxEntities,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Combine property filter configurations
|
|
70
|
+
*/
|
|
71
|
+
function combinePropertyFilters(base, override) {
|
|
72
|
+
if (!base && !override)
|
|
73
|
+
return undefined;
|
|
74
|
+
if (!base)
|
|
75
|
+
return override;
|
|
76
|
+
if (!override)
|
|
77
|
+
return base;
|
|
78
|
+
return [...base, ...override];
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Combine arrays, handling undefined values
|
|
82
|
+
*/
|
|
83
|
+
function combineArrays(base, override) {
|
|
84
|
+
if (!base && !override)
|
|
85
|
+
return undefined;
|
|
86
|
+
if (!base)
|
|
87
|
+
return override;
|
|
88
|
+
if (!override)
|
|
89
|
+
return base;
|
|
90
|
+
return [...base, ...override];
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Convert property filter by ID rules to PropertyFilterConfig
|
|
94
|
+
*/
|
|
95
|
+
function convertPropertyFiltersByIds(rules) {
|
|
96
|
+
return rules.flatMap((rule) => rule.entityIds.map((entityId) => ({
|
|
97
|
+
selector: { '@id': entityId },
|
|
98
|
+
include: rule.include,
|
|
99
|
+
exclude: rule.exclude,
|
|
100
|
+
})));
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Convert property filter by type rules to PropertyFilterConfig
|
|
104
|
+
*/
|
|
105
|
+
function convertPropertyFiltersByTypes(rules) {
|
|
106
|
+
return rules.flatMap((rule) => rule.entityTypes.map((entityType) => ({
|
|
107
|
+
selector: { '@type': entityType },
|
|
108
|
+
include: rule.include,
|
|
109
|
+
exclude: rule.exclude,
|
|
110
|
+
})));
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Build complete property filter configuration from all sources
|
|
114
|
+
*/
|
|
115
|
+
function buildPropertyFilterConfig(config) {
|
|
116
|
+
const filters = [];
|
|
117
|
+
// Add base property filters
|
|
118
|
+
if (config.propertyFilters) {
|
|
119
|
+
filters.push(...config.propertyFilters);
|
|
120
|
+
}
|
|
121
|
+
// Add property filters by IDs
|
|
122
|
+
if (config.propertyFiltersByIds) {
|
|
123
|
+
filters.push(...convertPropertyFiltersByIds(config.propertyFiltersByIds));
|
|
124
|
+
}
|
|
125
|
+
// Add property filters by types
|
|
126
|
+
if (config.propertyFiltersByTypes) {
|
|
127
|
+
filters.push(...convertPropertyFiltersByTypes(config.propertyFiltersByTypes));
|
|
128
|
+
}
|
|
129
|
+
return filters.length > 0 ? filters : undefined;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Validate configuration for common issues
|
|
133
|
+
*/
|
|
134
|
+
function validateConfig(config) {
|
|
135
|
+
const errors = [];
|
|
136
|
+
// Check for conflicting include/exclude types
|
|
137
|
+
if (config.filters?.includeTypes && config.filters?.excludeTypes) {
|
|
138
|
+
const overlap = config.filters.includeTypes.filter((type) => config.filters.excludeTypes.includes(type));
|
|
139
|
+
if (overlap.length > 0) {
|
|
140
|
+
errors.push(`Conflicting include/exclude types: ${overlap.join(', ')}`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
// Check for conflicting include/exclude IDs
|
|
144
|
+
if (config.filters?.includeIds && config.filters?.excludeIds) {
|
|
145
|
+
const overlap = config.filters.includeIds.filter((id) => config.filters.excludeIds.includes(id));
|
|
146
|
+
if (overlap.length > 0) {
|
|
147
|
+
errors.push(`Conflicting include/exclude IDs: ${overlap.join(', ')}`);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
// Check for invalid maxEntities
|
|
151
|
+
if (config.filters?.maxEntities !== undefined && config.filters.maxEntities < 1) {
|
|
152
|
+
errors.push('maxEntities must be greater than 0');
|
|
153
|
+
}
|
|
154
|
+
return errors;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Apply populate configuration to entities in the graph
|
|
158
|
+
*/
|
|
159
|
+
function applyPopulateConfig(graph, populateConfig) {
|
|
160
|
+
return graph.map((entity) => {
|
|
161
|
+
const entityId = entity['@id'];
|
|
162
|
+
const populateRules = populateConfig[entityId];
|
|
163
|
+
if (!populateRules || populateRules.length === 0) {
|
|
164
|
+
return entity;
|
|
165
|
+
}
|
|
166
|
+
// Create a copy of the entity to avoid mutation
|
|
167
|
+
const populatedEntity = { ...entity };
|
|
168
|
+
// Apply each populate rule
|
|
169
|
+
for (const rule of populateRules) {
|
|
170
|
+
populatedEntity[rule.property] = rule.entities;
|
|
171
|
+
}
|
|
172
|
+
return populatedEntity;
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Validate runtime configuration for critical errors only
|
|
177
|
+
* This is more lenient than the general validateConfig to handle runtime overrides
|
|
178
|
+
*/
|
|
179
|
+
function validateRuntimeConfig(config) {
|
|
180
|
+
const errors = [];
|
|
181
|
+
// Check for baseGraph requirement
|
|
182
|
+
if (!config.baseGraph) {
|
|
183
|
+
errors.push('baseGraph is required');
|
|
184
|
+
}
|
|
185
|
+
else if (!Array.isArray(config.baseGraph)) {
|
|
186
|
+
errors.push('baseGraph must be an array');
|
|
187
|
+
}
|
|
188
|
+
// Only check for critical errors that would break processing
|
|
189
|
+
if (config.filters?.maxEntities !== undefined && config.filters.maxEntities < 1) {
|
|
190
|
+
errors.push('maxEntities must be greater than 0');
|
|
191
|
+
}
|
|
192
|
+
return errors;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Type guard to check if an entity matches a type
|
|
196
|
+
*/
|
|
197
|
+
function entityHasType(entity, type) {
|
|
198
|
+
const entityType = entity['@type'];
|
|
199
|
+
if (!entityType)
|
|
200
|
+
return false;
|
|
201
|
+
if (Array.isArray(entityType)) {
|
|
202
|
+
return entityType.includes(type);
|
|
203
|
+
}
|
|
204
|
+
return entityType === type;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Type guard to check if an entity has any of the specified types
|
|
208
|
+
*/
|
|
209
|
+
function entityHasAnyType(entity, types) {
|
|
210
|
+
return types.some((type) => entityHasType(entity, type));
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Get all types from an entity as an array
|
|
214
|
+
*/
|
|
215
|
+
function getEntityTypes(entity) {
|
|
216
|
+
const entityType = entity['@type'];
|
|
217
|
+
if (!entityType)
|
|
218
|
+
return [];
|
|
219
|
+
return Array.isArray(entityType) ? entityType : [entityType];
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Apply filters to a JSON-LD graph (copied from head-manager/filters.ts for self-containment)
|
|
223
|
+
*/
|
|
224
|
+
function filterJsonLdGraph(graph, options) {
|
|
225
|
+
let filtered = [...graph];
|
|
226
|
+
// Apply type inclusion filter
|
|
227
|
+
if (options.includeTypes && options.includeTypes.length > 0) {
|
|
228
|
+
filtered = filtered.filter((entity) => {
|
|
229
|
+
const type = entity['@type'];
|
|
230
|
+
if (!type)
|
|
231
|
+
return false;
|
|
232
|
+
const types = Array.isArray(type) ? type : [type];
|
|
233
|
+
return types.some((t) => options.includeTypes.includes(t));
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
// Apply type exclusion filter
|
|
237
|
+
if (options.excludeTypes && options.excludeTypes.length > 0) {
|
|
238
|
+
filtered = filtered.filter((entity) => {
|
|
239
|
+
const type = entity['@type'];
|
|
240
|
+
if (!type)
|
|
241
|
+
return true;
|
|
242
|
+
const types = Array.isArray(type) ? type : [type];
|
|
243
|
+
return !types.some((t) => options.excludeTypes.includes(t));
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
// Apply ID inclusion filter
|
|
247
|
+
if (options.includeIds && options.includeIds.length > 0) {
|
|
248
|
+
filtered = filtered.filter((entity) => entity['@id'] && options.includeIds.includes(entity['@id']));
|
|
249
|
+
}
|
|
250
|
+
// Apply ID exclusion filter
|
|
251
|
+
if (options.excludeIds && options.excludeIds.length > 0) {
|
|
252
|
+
filtered = filtered.filter((entity) => !entity['@id'] || !options.excludeIds.includes(entity['@id']));
|
|
253
|
+
}
|
|
254
|
+
// Apply required properties filter
|
|
255
|
+
if (options.requiredProperties && options.requiredProperties.length > 0) {
|
|
256
|
+
filtered = filtered.filter((entity) => options.requiredProperties.every((prop) => prop in entity));
|
|
257
|
+
}
|
|
258
|
+
// Apply excluded properties filter (handle both old and new property names)
|
|
259
|
+
const excludeProps = options.excludeEntitiesWithProperties || options.excludeProperties;
|
|
260
|
+
if (excludeProps && excludeProps.length > 0) {
|
|
261
|
+
filtered = filtered.filter((entity) => !excludeProps.some((prop) => prop in entity));
|
|
262
|
+
}
|
|
263
|
+
// Apply custom filter
|
|
264
|
+
if (options.customFilter) {
|
|
265
|
+
filtered = filtered.filter(options.customFilter);
|
|
266
|
+
}
|
|
267
|
+
// Apply max entities limit
|
|
268
|
+
if (options.maxEntities && options.maxEntities > 0) {
|
|
269
|
+
filtered = filtered.slice(0, options.maxEntities);
|
|
270
|
+
}
|
|
271
|
+
return filtered;
|
|
272
|
+
}
|