schema-dts

repository·main·Indexed 22 days ago

https://github.com/google/schema-dts

TypeScript definitions for the Schema.org vocabulary in JSON-LD format. The project includes schema-dts for type definitions, schema-dts-lib for root types of JSON-LD vocabularies, and schema-dts-gen, a CLI tool to generate custom TypeScript typings from Schema.org-compatible ontologies provided via .nt (NTriple) files.

Tokens
6.8K
Snippets
18
Records
33
Agent score
78%

What's inside schema-dts

  1. Create interconnected JSON-LD graphs with Graph and @id

    main

    For complex JSON-LD structures with interconnected nodes, use the Graph type. This allows you to define a top-level @graph array where nodes can be referenced by their @id. You can use an @id stub (e.g., { '@id': '...' }) to link different entities within the graph without re-defining them inline.

    import type {Graph} from 'schema-dts';
    
    const graph: Graph = {
      '@context': 'https://schema.org',
      '@graph': [
        {
          '@type': 'Person',
          '@id': 'https://my.site/#alyssa',
          name: 'Alyssa P. Hacker',
          hasOccupation: {
            '@type': 'Occupation',
            name: 'LISP Hacker',
            qualifications: 'Knows LISP',
          },
          mainEntityOfPage: {'@id': 'https://my.site/about/#page'},
          subjectOf: {'@id': 'https://my.site/about/#page'},
        },
        {
          '@type': 'AboutPage',
          '@id': 'https://my.site/#site',
          url: 'https://my.site',
          name: "Alyssa P. Hacker's Website",
          inLanguage: 'en-US',
          description: 'The personal website of LISP legend Alyssa P. Hacker',
          mainEntity: {'@id': 'https://my.site/#alyssa'},
        },
        {
          '@type': 'WebPage',
          '@id': 'https://my.site/about/#page',
          url: 'https://my.site/about/',
          name: "About | Alyssa P. Hacker's Website",
          inLanguage: 'en-US',
          isPartOf: {
            '@id': 'https://my.site/#site',
          },
          about: {'@id': 'https://my.site/#alyssa'},
          mainEntity: {'@id': 'https://my.site/#alyssa'},
        },
      ],
    };
  2. Use the Graph type for interconnected JSON-LD nodes

    main

    For complex JSON-LD structures using the '@graph' property, use the Graph type. This allows you to define nodes with @id and reference them elsewhere in the graph using ID stubs.

    import type {Graph} from 'schema-dts';
    
    const graph: Graph = {
      '@context': 'https://schema.org',
      '@graph': [
        {
          '@type': 'Person',
          '@id': 'https://my.site/#alyssa',
          name: 'Alyssa P. Hacker',
          hasOccupation: {
            '@type': 'Occupation',
            name: 'LISP Hacker',
            qualifications: 'Knows LISP',
          },
          mainEntityOfPage: {'@id': 'https://my.site/about/#page'},
          subjectOf: {'@id': 'https://my.site/about/#page'},
        },
        {
          '@type': 'AboutPage',
          '@id': 'https://my.site/#site',
          url: 'https://my.site',
          name: "Alyssa P. Hacker's Website",
          inLanguage: 'en-US',
          description: 'The personal website of LISP legend Alyssa P. Hacker',
          mainEntity: {'@id': 'https://my.site/#alyssa'},
        },
        {
          '@type': 'WebPage',
          '@id': 'https://my.site/about/#page',
          url: 'https://my.site/about/',
          name: "About | Alyssa P. Hacker's Website",
          inLanguage: 'en-US',
          isPartOf: {
            '@id': 'https://my.site/#site',
          },
          about: {'@id': 'https://my.site/#alyssa'},
          mainEntity: {'@id': 'https://my.site/#alyssa'},
        },
      ],
    };
  3. Integrate schema-dts with Astro using inline script tags

    main

    In Astro, you can render JSON-LD directly within a component's template using an inline <script> tag. Use a helper function to escape characters for XSS safety and pass the result to the set:html directive.

    ---
    import type {FAQPage, WithContext} from 'schema-dts';
    
    const faq: WithContext<FAQPage> = {
      '@context': 'https://schema.org',
      '@type': 'FAQPage',
      mainEntity: [
        {
          '@type': 'Question',
          name: 'Do you ship internationally?',
          acceptedAnswer: {
            '@type': 'Answer',
            text: 'Yes, we ship to over 50 countries.',
          },
        },
      ],
    };
    
    function safeJsonLd(data: object): string {
      return JSON.stringify(data)
        .replace(/</g, '\\u003C')
        .replace(/>/g, '\\u003E')
        .replace(/&/g, '\\u0026')
        .replace(/'/g, '\\u0027');
    }
    ---
    
    <script type="application/ld+json" set:html={safeJsonLd(faq)} />
  4. Integrate schema-dts with Next.js using the Script component

    main

    In Next.js, use the built-in <Script> component to inject JSON-LD. To prevent XSS vulnerabilities, you must escape characters that could break out of a <script> tag (specifically <, >, &, and ') before passing the string to dangerouslySetInnerHTML.

    import Script from 'next/script';
    import type {Article, WithContext} from 'schema-dts';
    
    function safeJsonLd(data: WithContext<Article>): string {
      return JSON.stringify(data)
        .replace(/</g, '\\u003C')
        .replace(/>/g, '\\u003E')
        .replace(/&/g, '\\u0026')
        .replace(/'/g, '\\u0027');
    }
    
    export default function BlogPost() {
      const article: WithContext<Article> = {
        '@context': 'https://schema.org',
        '@type': 'Article',
        headline: 'How to choose a leather wallet',
        datePublished: '2025-03-01',
        author: {'@type': 'Person', name: 'Jane Smith'},
      };
    
      return (
        <>
          <Script
            id="article-jsonld"
            type="application/ld+json"
            dangerouslySetInnerHTML={{__html: safeJsonLd(article)}}
          />
          <article>{/* page content */}</article>
        </>
      );
    }
  5. Integrate schema-dts with React using react-schemaorg

    main

    To use schema-dts types in a React application, use the react-schemaorg library. It provides a <JsonLd> component that accepts a generic type from schema-dts and handles XSS-safe serialization of your JSON-LD data automatically.

    import {JsonLd} from 'react-schemaorg';
    import type {Product} from 'schema-dts';
    
    export function ProductPage() {
      return (
        <JsonLd<Product>
          item={{
            '@context': 'https://schema.org',
            '@type': 'Product',
            name: 'Classic Leather Wallet',
            offers: {
              '@type': 'Offer',
              price: 89,
              priceCurrency: 'USD',
            },
          }}
        />
      );
    }
  6. Integrate schema-dts with Svelte using <svelte:head>

    main

    In Svelte, use the <svelte:head> component to inject JSON-LD into the document <head>. Ensure you use an escaping pattern for the JSON string and inject it using the {@html ...} tag.

    <script lang="ts">
      import type {Organization, WithContext} from 'schema-dts';
    
      const org: WithContext<Organization> = {
        '@context': 'https://schema.org',
        '@type': 'Organization',
        name: 'Acme Corp',
        url: 'https://acme.com',
        logo: 'https://acme.com/logo.png',
      };
    
      function safeJsonLd(data: object): string {
        return JSON.stringify(data)
          .replace(/</g, '\\u003C')
          .replace(/>/g, '\\u003E')
          .replace(/&/g, '\\u0026')
          .replace(/'/g, '\\u0027');
      }
    </script>
    
    <svelte:head>
      {@html `<script type="application/ld+json">${safeJsonLd(org)}</script>`}
    </svelte:head>
  7. Inject JSON-LD in vanilla TypeScript

    main

    For framework-agnostic environments, you can inject JSON-LD by manually creating a <script> element, setting its type to application/ld+json, and appending it to the document head.

    import type {WebSite, WithContext} from 'schema-dts';
    
    const site: WithContext<WebSite> = {
      '@context': 'https://schema.org',
      '@type': 'WebSite',
      name: 'Acme Corp',
      url: 'https://acme.com',
    };
    
    const script = document.createElement('script');
    script.type = 'application/ld+json';
    script.textContent = JSON.stringify(site);
    document.head.appendChild(script);
  8. Install and use schema-dts-gen

    main

    To generate TypeScript definitions for JSON-LD conforming to a specific ontology, install schema-dts-gen and run the CLI tool. You must provide an HTTPS URL to an .nt (NTriple) file that declares your ontology. The ontology must be compatible with Schema.org, include Schema.org DataTypes, and specify a top-level Thing type.

    npm install --save-dev schema-dts-gen
    npx schema-dts-gen --ontology=https://schema.org/version/latest/schemaorg-all-https.nt
  9. Parse and filter triples in `schema-dts-gen`

    main

    The reader.ts module provides utilities for ingesting RDF data (triples) into the schema-dts-gen pipeline. It supports both remote HTTPS URLs and local file paths, converting the raw data into an N3 Store.

    Key behaviors:

    • Redirect Support: load() automatically follows HTTP redirects.
    • Filtering: The process() function removes NamedNode subjects that use the file:/// URI scheme to prevent local file references from entering the schema graph.