diff --git a/CHANGELOG.md b/CHANGELOG.md index 52e3884..1a24f1c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## 1.9.0 + +A site that belongs to a larger property can name the parent's Organization. The default output is unchanged: a configuration without `organization['@id']` emits the same graph as 1.8.0, byte for byte (`test/fixtures/graphs-1.7.1.json` still passes). + +Added: + +- `themeConfig.structuredData.organization['@id']` is honoured by every reference to the organization: `WebSite.publisher`, the `Article` and `TechArticle` `publisher`, and the `publisher` the native-article supplement adds in `'reuse'` mode. The node's own `@id` could already be overridden (the block is spread last), but the references stayed `/#organization`, so an override left `publisher` pointing at a node that was not in the graph. Set `@id`, `name` and `url` to the parent site's values; see [Organization contact details](README.md#organization-contact-details). +- A set `organization['@id']` must be an absolute `http` or `https` IRI. Anything else (a relative or fragment-only reference, another scheme, a non-string) fails the build at config time with a message naming the option. +- Tests: an override on another origin in both `nativeStructuredData` modes (every `publisher` references it and the default id appears nowhere on the page), the default id set explicitly (same output as unset), and the validator. + ## 1.8.0 Composing with the JSON-LD Docusaurus writes itself, and image dimensions that describe the right image ([#4](https://github.com/stackql-labs/docusaurus-plugin-structured-data/issues/4)). With no new option set, a 1.7.1 configuration emits the same graph except where listed under Fixed. diff --git a/README.md b/README.md index 692878d..4391ce9 100644 --- a/README.md +++ b/README.md @@ -99,7 +99,7 @@ All settings below belong in `themeConfig.structuredData`. The plugin accepts on | `featuredImageDimensions` | `{width: number, height: number}` | Unset. The size of `themeConfig.image`, stated as `ImageObject.width` and `height` only on pages whose image is that default. Both values must be finite and greater than zero. | | `nativeStructuredData` | `'ignore'` or `'reuse'` | `'ignore'`. What to do about JSON-LD a page already has; see [Docusaurus's own structured data](#docusauruss-own-structured-data). | | `authors` | object keyed by author name | `{}`. Author details for `Article`; see Authors below. | -| `organization` | object | Overrides or extends the generated `Organization` node. | +| `organization` | object | Overrides or extends the generated `Organization` node. A set `@id` (absolute http(s) IRI) is used by every reference to the organization; see [Organization contact details](#organization-contact-details). | | `website` | object | Overrides or extends the generated `WebSite` node. | | `webpage` | object | Extends `WebPage`. `inLanguage` defaults to `en-US` on the default locale and to the locale's `htmlLang` in every other locale of an i18n site; `datePublished` is a site-wide fallback. Generated page fields take precedence. | | `softwareSourceCode` | object | Unset. Emits a site-wide node when configured; requires an HTTP(S) `codeRepository` URL. | @@ -309,6 +309,18 @@ contactPoint: { }, ``` +A site that belongs to a larger property (a product microsite on its own subdomain, say) can name the parent's Organization instead of describing a second one. Set `@id`, `name` and `url` to the values the parent site's graph carries, and `logo` and `sameAs` too if you want the node to match it: + +```js +organization: { + '@id': 'https://example.com/#organization', + name: 'Example', + url: 'https://example.com', +}, +``` + +The Organization node and every reference to it (`WebSite.publisher`, the `Article` and `TechArticle` `publisher`, and the `publisher` added to a reused native article) use that `@id`. It must be an absolute `http` or `https` IRI; anything else fails the build. Without it the `@id` is `/#organization`. + ### Open-source product: SoftwareSourceCode and SoftwareApplication Two site-wide blocks describe the product the site documents: @@ -736,8 +748,9 @@ non-empty name and at least one step with non-empty `name` and `text`. Software application payloads must be `true` or an object; supplied `applicationCategory` values must be in the plugin's supported list. An invalid `softwareSourceCode.codeRepository`, malformed image dimensions, -or a `nativeStructuredData` value other than `'ignore'` or `'reuse'` also -fails the build. +an `organization['@id']` that is not an absolute http(s) IRI, or a +`nativeStructuredData` value other than `'ignore'` or `'reuse'` also fails +the build. These checks validate selected inputs, not the full schema.org vocabulary or search-engine eligibility. Optional fields and pass-through properties @@ -747,7 +760,7 @@ still need appropriate values. ```bash npm install -npm test # node --test: node builders, validators, dates, breadcrumbs, route matching, plugin options, both nativeStructuredData modes +npm test # node --test: node builders, validators, dates, breadcrumbs, route matching, plugin options, both nativeStructuredData modes, organization @id ``` The pure logic lives in `src/lib.js`; `src/index.js` is the Docusaurus lifecycle around it. `test/fixtures/site` holds four pages with the `` Docusaurus 3.9 renders, the theme's own JSON-LD included, and `test/fixtures/graphs-1.7.1.json` is what plugin 1.7.1 wrote for them: the default output is compared against it. diff --git a/package-lock.json b/package-lock.json index 3e9eef2..d447a50 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@stackql/docusaurus-plugin-structured-data", - "version": "1.8.0", + "version": "1.9.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@stackql/docusaurus-plugin-structured-data", - "version": "1.8.0", + "version": "1.9.0", "license": "MIT", "dependencies": { "jsdom": "^21.0.0" diff --git a/package.json b/package.json index 44ea78e..dc09d64 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@stackql/docusaurus-plugin-structured-data", - "version": "1.8.0", + "version": "1.9.0", "description": "A plugin which adds structured data to your docusaurus site.", "main": "src/index.js", "publishConfig": { diff --git a/src/index.js b/src/index.js index b944c17..d2b908f 100644 --- a/src/index.js +++ b/src/index.js @@ -13,6 +13,8 @@ const { validateTechArticleRoutePrefixes, validateFeaturedImageDimensions, validateNativeStructuredData, + validateOrganizationId, + resolveOrganizationId, validatePluginOptions, buildFaqNode, buildHowToNode, @@ -257,6 +259,13 @@ module.exports = function (context, options) { validateSoftwareSourceCode(structuredData.softwareSourceCode); const softwareApplicationDefaults = structuredData.softwareApplication || null; + // The Organization's @id, used by the node itself and by every + // reference to it (WebSite and Article publisher, the native-article + // supplement). A site that belongs to a larger property sets it to the + // parent's; the default is /#organization. + validateOrganizationId(structuredData.organization); + const organizationId = resolveOrganizationId(structuredData.organization, siteConfig.url); + // Exact routes or globs ("/providers/*", "/registry/**"), matched against // the route with and without siteConfig.baseUrl. const isExcludedRoute = routeMatcher(structuredData.excludedRoutes || []); @@ -278,7 +287,7 @@ module.exports = function (context, options) { const orgData = { '@type': 'Organization', - '@id': `${baseUrl}/#organization`, + '@id': organizationId, name: `${orgName}`, url: `${baseUrl}`, ...normalizeOrganization(structuredData.organization, (w) => console.warn(w)), @@ -298,7 +307,7 @@ module.exports = function (context, options) { url: `${baseUrl}`, description: `${siteConfig.tagline}`, publisher: { - '@id': `${baseUrl}/#organization`, + '@id': organizationId, }, potentialAction: [ { @@ -809,7 +818,7 @@ module.exports = function (context, options) { articleSupplement = buildNativeArticleSupplement(nativeArticle, { webPageId: `${idBase}/#webpage`, - organizationId: `${baseUrl}/#organization`, + organizationId, dateModified, }); if (articleSupplement) { @@ -852,7 +861,7 @@ module.exports = function (context, options) { }, wordCount: wordCount, publisher: { - '@id': `${baseUrl}/#organization` + '@id': organizationId }, image: { '@id': `${idBase}/#primaryimage` diff --git a/src/lib.js b/src/lib.js index 57f28a9..6a03e91 100644 --- a/src/lib.js +++ b/src/lib.js @@ -196,6 +196,35 @@ function validateNativeStructuredData(mode) { ); } +// themeConfig.structuredData.organization['@id']: optional. A site that is +// part of a larger property names the parent's Organization here, and every +// reference to the organization follows it, so the value has to be an IRI +// that resolves the same from any page: absolute, http or https. +function validateOrganizationId(org) { + if (!org || typeof org !== 'object' || org['@id'] === undefined) return; + const id = org['@id']; + let parsed = null; + if (typeof id === 'string') { + try { + parsed = new URL(id); + } catch { + parsed = null; + } + } + if (!parsed || (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')) { + throw new Error( + `${TAG} themeConfig.structuredData.organization['@id'] must be an absolute http(s) IRI (e.g. "https://example.com/#organization"), got ${JSON.stringify(id)}` + ); + } +} + +// The @id of the Organization node and of every reference to it: the +// configured organization['@id'], else /#organization. +function resolveOrganizationId(org, baseUrl) { + if (org && typeof org === 'object' && typeof org['@id'] === 'string') return org['@id']; + return `${baseUrl}/#organization`; +} + // Docusaurus hands every plugin an options object; this one is configured // under themeConfig.structuredData only. Anything else passed as a plugin // option used to be ignored silently, which hid misplaced configuration. @@ -692,6 +721,8 @@ module.exports = { validateTechArticleRoutePrefixes, validateFeaturedImageDimensions, validateNativeStructuredData, + validateOrganizationId, + resolveOrganizationId, validatePluginOptions, buildFaqNode, buildHowToNode, diff --git a/test/lib.test.js b/test/lib.test.js index 14046a5..dce9c51 100644 --- a/test/lib.test.js +++ b/test/lib.test.js @@ -205,6 +205,24 @@ test('routeMatcher: exact routes and globs, with or without a trailing slash', ( assert.equal(lib.routeMatcher(undefined)('/x'), false); }); +test("validateOrganizationId: optional, but a set organization['@id'] must be an absolute http(s) IRI", () => { + for (const org of [undefined, null, {}, { name: 'X' }, { '@id': 'https://stackql.io/#organization' }, { '@id': 'http://a.b/#o' }]) { + assert.doesNotThrow(() => lib.validateOrganizationId(org), JSON.stringify(org)); + } + for (const id of ['/#organization', 'stackql.io/#organization', 'ftp://a.b/#o', '', null, 1]) { + assert.throws(() => lib.validateOrganizationId({ '@id': id }), /organization\['@id'\] must be an absolute http\(s\) IRI/, JSON.stringify(id)); + } +}); + +test("resolveOrganizationId: organization['@id'] when set, else /#organization", () => { + assert.equal(lib.resolveOrganizationId(undefined, 'https://example.com'), 'https://example.com/#organization'); + assert.equal(lib.resolveOrganizationId({ name: 'X' }, 'https://example.com'), 'https://example.com/#organization'); + assert.equal( + lib.resolveOrganizationId({ '@id': 'https://stackql.io/#organization' }, 'https://example.com'), + 'https://stackql.io/#organization', + ); +}); + test('validatePluginOptions rejects anything but id', () => { assert.doesNotThrow(() => lib.validatePluginOptions(undefined)); assert.doesNotThrow(() => lib.validatePluginOptions({ id: 'default' })); diff --git a/test/organization.test.js b/test/organization.test.js new file mode 100644 index 0000000..114ec3b --- /dev/null +++ b/test/organization.test.js @@ -0,0 +1,117 @@ +// organization['@id']: a site that belongs to a larger property names the +// parent's Organization, and every reference to the organization follows +// it. Runs over the fixture site in test/fixtures. The default output (no +// @id set) is compared against graphs-1.7.1.json in native.test.js. + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const plugin = require('../src/index'); +const { ROUTES, BUILD_TIME, structuredData, context, buildSite, readPage } = require('./fixtures/site'); + +const freezeClock = (t) => t.mock.timers.enable({ apis: ['Date'], now: Date.parse(BUILD_TIME) }); + +const SITE_ORG = 'https://example.com/#organization'; +const PARENT_ORG = 'https://parent.example.org/#organization'; +const DOC = '/docs/guides/install'; +const POST = '/blog/post'; + +// The fixture's organization block with the parent's identity on top. +const parentOrganization = { + ...structuredData().organization, + '@id': PARENT_ORG, + name: 'Parent', + url: 'https://parent.example.org', +}; + +const typed = (nodes, type) => nodes.filter((n) => n['@type'] === type); + +// Every `publisher` value anywhere in a graph, nested nodes included. +function publishers(value, found = []) { + if (Array.isArray(value)) { + value.forEach((v) => publishers(v, found)); + } else if (value && typeof value === 'object') { + for (const [key, v] of Object.entries(value)) { + if (key === 'publisher') found.push(v); + publishers(v, found); + } + } + return found; +} + +test("organization['@id'] set to the default is the same as leaving it unset", async (t) => { + freezeClock(t); + const unset = await buildSite(plugin); + const explicit = await buildSite(plugin, { organization: { ...structuredData().organization, '@id': SITE_ORG } }); + for (const route of ROUTES) { + assert.equal((await readPage(explicit, route)).html, (await readPage(unset, route)).html, route); + } +}); + +for (const mode of ['ignore', 'reuse']) { + test(`'${mode}': an organization['@id'] on another origin is referenced by every publisher`, async () => { + const outDir = await buildSite(plugin, { nativeStructuredData: mode, organization: parentOrganization }); + let publisherCount = 0; + for (const route of ROUTES) { + const page = await readPage(outDir, route); + + const [org] = typed(page.graph, 'Organization'); + assert.equal(org['@id'], PARENT_ORG, route); + assert.equal(org.name, 'Parent', route); + assert.equal(org.url, 'https://parent.example.org', route); + assert.deepEqual(typed(page.graph, 'WebSite')[0].publisher, { '@id': PARENT_ORG }, route); + + const refs = publishers(page.graph); + assert.ok(refs.length > 0, `${route}: no publisher in the graph`); + for (const ref of refs) assert.deepEqual(ref, { '@id': PARENT_ORG }, route); + publisherCount += refs.length; + + // Not in the plugin's graph, nor anywhere else on the page. + assert.equal(JSON.stringify(page.graph).includes(SITE_ORG), false, `${route}: graph still names ${SITE_ORG}`); + assert.equal(page.html.includes(SITE_ORG), false, `${route}: page still names ${SITE_ORG}`); + } + // WebSite on all four pages, plus the article publisher on DOC and POST. + assert.equal(publisherCount, ROUTES.length + 2); + }); +} + +test("'ignore': Article and TechArticle publishers follow organization['@id']", async () => { + const outDir = await buildSite(plugin, { organization: parentOrganization }); + const [techArticle] = typed((await readPage(outDir, DOC)).graph, 'TechArticle'); + const [article] = typed((await readPage(outDir, POST)).graph, 'Article'); + assert.deepEqual(techArticle.publisher, { '@id': PARENT_ORG }); + assert.deepEqual(article.publisher, { '@id': PARENT_ORG }); +}); + +test("'reuse': the native-article supplement's publisher follows organization['@id']", async () => { + const outDir = await buildSite(plugin, { nativeStructuredData: 'reuse', organization: parentOrganization }); + const page = await readPage(outDir, POST); + const supplement = page.graph.find((n) => n['@id'] === 'https://example.com/blog/post'); + assert.ok(supplement, 'no supplement node for the BlogPosting'); + assert.equal(supplement['@type'], undefined); + assert.deepEqual(supplement.publisher, { '@id': PARENT_ORG }); +}); + +test("an organization['@id'] that is not an absolute http(s) IRI fails at config time", () => { + for (const id of [ + '/#organization', + '#organization', + 'stackql.io/#organization', + '//stackql.io/#organization', + 'ftp://stackql.io/#organization', + 'mailto:info@stackql.io', + 'not a url', + '', + null, + 42, + { '@id': 'https://stackql.io/#organization' }, + ]) { + assert.throws( + () => plugin(context({ organization: { '@id': id } }), { id: 'default' }), + /themeConfig\.structuredData\.organization\['@id'\] must be an absolute http\(s\) IRI/, + JSON.stringify(id), + ); + } + for (const id of ['https://stackql.io/#organization', 'http://example.org/#org', undefined]) { + assert.doesNotThrow(() => plugin(context({ organization: { '@id': id } }), { id: 'default' }), String(id)); + } +});