Repository navigation
docs(jsonldjs): add agent skill and update README #166
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| --- | ||
| name: jsonldjs | ||
| description: Build, filter, extract subgraphs, inline references, and validate Schema.org JSON-LD graphs with the jsonldjs package (packages/jsonld-tools). Use when authoring or querying JSON-LD graphs, emitting <script type="application/ld+json"> tags, or debugging JSON-LD references. | ||
| --- | ||
|
|
||
| # jsonldjs | ||
|
|
||
| Build and query JSON-LD `@graph` arrays (`JsonLdEntity[]`, each with `'@id': string` and optional `'@type': string | string[]`) without external dependencies or JSON-LD context expansion. | ||
|
|
||
| ## Builder and reusable configs | ||
|
|
||
| Use `createJsonLdConfig()` for reusable, composable presets and `createJsonLdBuilder()` to process a graph and emit JSON-LD: | ||
|
|
||
| ```typescript | ||
| import { createJsonLdBuilder, createJsonLdConfig } from 'jsonldjs'; | ||
|
|
||
| const baseConfig = createJsonLdConfig() | ||
| .baseGraph(graph) | ||
| .filterPropertiesByIds(['org:hyperweb'], { exclude: ['subjectOf'] }); | ||
|
|
||
| const html = createJsonLdBuilder() | ||
| .mergeConfig(baseConfig.getConfig()) | ||
| .subgraph(['org:hyperweb']) | ||
| .excludeTypes(['ImageObject']) | ||
| .build({ prettyPrint: true, withScriptTag: true, scriptId: 'json-ld' }); | ||
| ``` | ||
|
|
||
| Key rules: | ||
|
|
||
| - Both `JsonLdConfigBuilder` and `JsonLdBuilder` are **immutable**: every fluent method returns a new instance. Always assign or chain the return value. | ||
| - `mergeConfig()` takes a `JsonLdConfig` object, not a builder — call `.getConfig()` on a `JsonLdConfigBuilder` before passing it. | ||
| - Graph processing is lazy and runs on `getCurrentGraph()` or `build(options)`. `build()` defaults to `{ prettyPrint: true, contextUrl: 'https://schema.org', withScriptTag: false }`. | ||
| - Array-based methods (`includeIds`, `excludeIds`, `includeTypes`, `excludeTypes`, `requiredProperties`, `excludeEntitiesWithProperties`, `subgraph`, `filterPropertiesByIds`, `filterPropertiesByTypes`, `addEntities`, `pipe`) **merge** with previous values. `customFilter()` and `maxEntities()` (must be `>= 1`) **replace** previous values. Use `clearIds()`, `clearTypes()`, `clearPropertyRequirements()`, `clearPropertyFilters()`, `clearSubgraph()`, or `clearAll()` (preserves `baseGraph`) to reset. | ||
|
|
||
| ## Processing order | ||
|
|
||
| `processGraph()` runs in a fixed sequence: | ||
|
|
||
| 1. **Validate** `baseGraph` is present and `maxEntities >= 1`. | ||
| 2. **Subgraph extraction** (if `subgraph()` is set): `extractSubgraphs()` traverses from roots with property filters applied during traversal, so excluded properties are not followed. | ||
| 3. **Property + entity filtering** (if any filters are set): property filters run first (skipped if already applied in step 2), then `filterJsonLdGraph()` runs `includeTypes` -> `excludeTypes` -> `includeIds` -> `excludeIds` -> `requiredProperties` -> `excludeEntitiesWithProperties` -> `customFilter` -> `maxEntities`. | ||
| 4. **Entity population** (`populateEntities(entityIds, populateConfig)`): copies only entries whose key is in `entityIds` and sets `entity[rule.property] = rule.entities` on matching entities. | ||
| 5. **Additional entities** (`addEntities()`): appended after filtering, bypassing all filters. | ||
| 6. **Custom pipes** (`pipe(fn)`): executed in registration order. | ||
|
|
||
| Property filter rules always preserve `@id`. When multiple rules match an entity, `exclude` accumulates and overrides `include`, while the last matching `include` wins. | ||
|
|
||
| ## Standalone graph utilities | ||
|
|
||
| All utilities operate directly on `JsonLdGraph` arrays. Reference detection recognizes `{ '@id': '...' }` objects and compact URI strings (`prefix:suffix`, no spaces) while ignoring `http://` and `https://` URLs. | ||
|
|
||
| - **Lookup**: `findEntity(graph, id)`, `findEntities(graph, ids)`, `findEntitiesByType(graph, type)`, `findReferencingEntities(graph, targetId, propertyFilters?)` | ||
| - **Traversal & inlining**: `extractReferences(entity)`, `extractSubgraph(graph, id, propertyFilters?)`, `extractSubgraphs(graph, ids, propertyFilters?)`, `extractSubgraphWithDepth(graph, id, maxDepth, propertyFilters?)`, `inlineReferences(entities, rootId?)` (breaks cycles with `{ '@id': id }`) | ||
| - **Filtering**: `filterJsonLdGraph(graph, options)`, `filterEntityProperties(entity, config)`, `filterGraphProperties(graph, config)` | ||
| - **Validation**: `findMissingReferences(graph)`, `findNestedEntities(graph)`, `findOrphans(graph)` | ||
|
|
||
| See the [package reference](../../../packages/jsonld-tools/README.md). | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -11,9 +11,12 @@ | |
| <a href="https://github.com/constructive-io/dev-utils/blob/main/LICENSE"> | ||
| <img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/> | ||
| </a> | ||
| <a href="https://www.npmjs.com/package/jsonldjs"> | ||
| <img height="20" src="https://img.shields.io/npm/v/jsonldjs.svg"/> | ||
| </a> | ||
| </p> | ||
|
|
||
| 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. | ||
| A powerful, generic JSON-LD builder with comprehensive entity and property filtering capabilities. Provides immutable configuration building and lazy graph processing with a fluent interface. | ||
|
|
||
| ## Installation | ||
|
|
||
|
|
@@ -132,10 +135,12 @@ const config = createJsonLdConfig() | |
|
|
||
| #### `createJsonLdBuilder()` | ||
|
|
||
| Creates a new builder that extends the configuration builder with graph processing capabilities. | ||
| Creates a new immutable builder that extends the configuration builder with lazy graph processing capabilities. Each chained method returns a new builder instance; processing runs when `getCurrentGraph()` or `build()` is called. | ||
|
|
||
| ```typescript | ||
| const builder = createJsonLdBuilder().baseGraph(graph).mergeConfig(config); | ||
| const builder = createJsonLdBuilder() | ||
| .baseGraph(graph) | ||
| .mergeConfig(config.getConfig()); | ||
| ``` | ||
|
|
||
| ### Configuration Methods | ||
|
|
@@ -148,8 +153,8 @@ All methods are inherited by the builder from the configuration builder: | |
| - `.excludeIds(ids: string[])` - Exclude entities with these IDs (merges with existing) | ||
| - `.includeTypes(types: string[])` - Include these entity types (merges with existing) | ||
| - `.excludeTypes(types: string[])` - Exclude these entity types (merges with existing) | ||
| - `.customFilter(fn: JsonLdFilter)` - Apply custom filter function | ||
| - `.maxEntities(max: number)` - Limit maximum number of entities | ||
| - `.customFilter(fn: JsonLdFilter)` - Apply custom filter function (replaces previous) | ||
| - `.maxEntities(max: number)` - Limit maximum number of entities (replaces previous; must be `>= 1`) | ||
| - `.requiredProperties(props: string[])` - Include entities with these properties (merges with existing) | ||
| - `.excludeEntitiesWithProperties(props: string[])` - Exclude entities with these properties (merges with existing) | ||
|
|
||
|
|
@@ -179,7 +184,7 @@ const otherConfig = createJsonLdConfig() | |
| const merged = baseConfig.mergeConfig(otherConfig); | ||
| // Result: includeTypes: ['Person', 'Organization'], excludeIds: ['test'] | ||
|
|
||
| // Main builder usage (processes graph immediately) | ||
| // Main builder usage (graph is processed lazily on build() or getCurrentGraph()) | ||
| const result = createJsonLdBuilder() | ||
| .baseGraph(graph) | ||
| .includeTypes(['Person']) | ||
|
|
@@ -198,6 +203,8 @@ const merged = baseConfig.mergeFilters(otherFilters); | |
| - `.filterPropertiesByIds(entityIds, rule)` - Filter properties for specific entity IDs | ||
| - `.filterPropertiesByTypes(entityTypes, rule)` - Filter properties for specific entity types | ||
|
|
||
| `@id` is always preserved. When multiple rules match an entity, `exclude` lists accumulate and take precedence over `include`, while the last matching `include` rule wins. | ||
|
|
||
| ```typescript | ||
| // Filter properties by entity ID | ||
| .filterPropertiesByIds(['org:hyperweb'], { | ||
|
|
@@ -213,9 +220,28 @@ const merged = baseConfig.mergeFilters(otherFilters); | |
| #### Graph Operations | ||
|
|
||
| - `.baseGraph(graph: JsonLdGraph)` - Set the base graph to process | ||
| - `.subgraph(rootIds: string[])` - Extract subgraph starting from these root IDs | ||
| - `.addEntities(entities: JsonLdEntity[])` - Add additional entities | ||
| - `.subgraph(rootIds: string[])` - Extract subgraph starting from these root IDs (merges with existing) | ||
| - `.populateEntities(entityIds: string[], populateConfig: PopulateConfig)` - Populate properties on matching entities with entity arrays (merges by entity ID) | ||
| - `.addEntities(entities: JsonLdEntity[])` - Add additional entities (appended after filtering) | ||
| - `.pipe(fn: PipeFunction)` - Add custom transformation function | ||
| - `.getConfig()` - Return a shallow copy of the current `JsonLdConfig` | ||
|
|
||
| ```typescript | ||
| // Populate properties on specific entities | ||
| const result = createJsonLdBuilder() | ||
| .baseGraph(graph) | ||
| .populateEntities(['org:hyperweb'], { | ||
| 'org:hyperweb': [ | ||
| { | ||
| property: 'employees', | ||
| entities: [ | ||
| { '@id': 'person:alice', '@type': 'Person', name: 'Alice' }, | ||
| ], | ||
| }, | ||
| ], | ||
| }) | ||
| .build(); | ||
| ``` | ||
|
|
||
| #### Builder-Only Methods | ||
|
|
||
|
|
@@ -235,23 +261,23 @@ interface BuildOptions { | |
|
|
||
| ## Advanced Usage | ||
|
|
||
| ### Complex Filtering Logic | ||
| ### Layered Filtering | ||
|
|
||
| The builder implements three distinct filtering paths based on configuration: | ||
| The builder applies filtering in two sequential layers (see [Options Processing Order](#options-processing-order) for full details): | ||
|
|
||
| 1. **Subgraph Mode**: When `subgraph()` is used, property filtering is applied during traversal | ||
| 2. **IncludeIds Mode**: When `includeIds()` is used, entities are filtered first, then additional filters applied | ||
| 3. **Global Mode**: Property filtering is applied first, then entity filtering | ||
| 1. **Subgraph Layer**: When `subgraph()` is set, connected entities are extracted from those roots with property filters applied during traversal (so excluded properties are not traversed). | ||
| 2. **Filter Layer**: If property filters were not already applied in Layer 1, they run first; then entity-level filters (`includeTypes`, `excludeTypes`, `includeIds`, `excludeIds`, `requiredProperties`, `excludeEntitiesWithProperties`, `customFilter`, `maxEntities`) run in order. | ||
|
|
||
| ```typescript | ||
| // Subgraph mode - follows references with property filtering | ||
| // Subgraph extraction + entity filtering combined | ||
| const result = createJsonLdBuilder() | ||
| .baseGraph(graph) | ||
| .subgraph(['org:hyperweb']) | ||
| .filterPropertiesByIds(['org:hyperweb'], { exclude: ['subjectOf'] }) | ||
| .excludeTypes(['ImageObject']) | ||
| .build(); | ||
|
|
||
| // IncludeIds mode - simple entity filtering | ||
| // Direct entity filtering (no subgraph extraction) | ||
| const result = createJsonLdBuilder() | ||
| .baseGraph(graph) | ||
| .includeIds(['org:hyperweb', 'person:john']) | ||
|
|
@@ -382,6 +408,58 @@ const result = createJsonLdBuilder() | |
|
|
||
| 5. **Sequential Pipe Execution**: Custom pipes are executed in the order they were added | ||
|
|
||
| ## Graph Utility Functions | ||
|
|
||
| In addition to the fluent builder, `jsonldjs` exports standalone functions for querying, traversing, filtering, and validating `JsonLdGraph` arrays (`JsonLdEntity[]`, where each entity has `'@id': string` and optional `'@type': string | string[]`). | ||
|
|
||
| Reference traversal detects both object references (`{ '@id': 'org:hyperweb' }`) and compact URI strings (`'org:hyperweb'`), while ignoring `http://` and `https://` URLs. | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Distinguish URL strings from object references.
|
||
|
|
||
| ### Lookup | ||
|
|
||
| - `findEntity(graph, id)` - Find a single entity by `@id` (`JsonLdEntity | undefined`) | ||
| - `findEntities(graph, ids)` - Find multiple entities matching an array of `@id` values | ||
| - `findEntitiesByType(graph, type)` - Find entities whose `@type` (string or array) includes `type` | ||
| - `findReferencingEntities(graph, targetId, propertyFilters?)` - Find entities that reference `targetId` | ||
|
|
||
| ### Subgraph & Reference Traversal | ||
|
|
||
| - `extractReferences(entity)` - Return a `Set<string>` of all `@id` references found in an entity's properties | ||
| - `extractSubgraph(graph, id, propertyFilters?)` - Recursively extract an entity and all referenced entities (handles cycles) | ||
| - `extractSubgraphs(graph, ids, propertyFilters?)` - Extract and deduplicate subgraphs for multiple root IDs | ||
| - `extractSubgraphWithDepth(graph, id, maxDepth, propertyFilters?)` - Extract a subgraph up to `maxDepth` hops (`maxDepth < 1` returns `[]`) | ||
| - `inlineReferences(entities, rootId?)` - Recursively replace `{ '@id': '...' }` references with full entities (breaks cycles by keeping `{ '@id': id }`); returns a single entity when `rootId` is given, or the full graph array otherwise | ||
|
|
||
| ### Filtering | ||
|
|
||
| - `filterJsonLdGraph(graph, options)` - Apply `JsonLdFilterOptions` to a graph directly | ||
| - `filterEntityProperties(entity, config)` - Apply `PropertyFilterConfig` rules to a single entity | ||
| - `filterGraphProperties(graph, config)` - Apply `PropertyFilterConfig` rules to every entity in a graph | ||
|
|
||
| ### Validation & Analysis | ||
|
|
||
| - `findMissingReferences(graph)` - Return sorted `@id` references that have no matching entity in the graph | ||
| - `findNestedEntities(graph)` - Find inline nested entity objects (objects with properties beyond `@id`) as normalization candidates | ||
| - `findOrphans(graph)` - Return sorted `@id` values of entities never referenced by any entity in the graph | ||
|
|
||
| ```typescript | ||
| import { | ||
| extractSubgraph, | ||
| findMissingReferences, | ||
| findOrphans, | ||
| inlineReferences, | ||
| } from 'jsonldjs'; | ||
|
|
||
| const missing = findMissingReferences(graph); | ||
| const orphans = findOrphans(graph); | ||
|
|
||
| const subgraph = extractSubgraph(graph, 'event:cosmoverse-2024'); | ||
| const expanded = inlineReferences(subgraph, 'event:cosmoverse-2024'); | ||
| ``` | ||
|
|
||
| ### Exported Types | ||
|
|
||
| `JsonLdEntity`, `JsonLdGraph`, `BuildOptions`, `JsonLdConfig`, `JsonLdFilterOptions`, `PopulateConfig`, plus classes `JsonLdBuilder` and `JsonLdConfigBuilder`. | ||
|
|
||
| ## Performance Considerations | ||
|
|
||
| - **Immutable Configurations**: Each configuration method returns a new object, enabling safe reuse | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Clarify the order of matching include rules.
If a type rule is registered before an ID rule, the type rule still wins:
buildPropertyFilterConfig()places type rules after ID rules. State this order here and in the README. Otherwise, users can remove the wrong properties. (raw.githubusercontent.com)