diff --git a/.vitepress/config.mts b/.vitepress/config.mts index 6b01568a4..a561d385c 100644 --- a/.vitepress/config.mts +++ b/.vitepress/config.mts @@ -1,6 +1,7 @@ import path from 'path'; import fs from 'fs'; import yaml from 'js-yaml'; +import { createRequire } from 'node:module'; import { defineConfig } from 'vitepress'; import { useSidebar } from 'vitepress-openapi'; import { loadSpec } from '../swagger/load'; @@ -20,6 +21,10 @@ import { capabilitySidebar } from '../utils/DeviceCapabilities'; const base = process.env.PREVIEW_BASE || "/" +// Keep the shared Node CLI helpers outside Vite's ESM config bundle. +const requireFromConfig = createRequire(import.meta.url); +const expandedProtocolPlugin = requireFromConfig(path.resolve(__dirname, './plugins/expanded-protocol.cjs')); +const expandedProtocol = requireFromConfig(path.resolve(__dirname, '../utils/expanded-protocol.cjs')); // Load protocol messages from YAML file const protocolYamlPath = path.resolve(__dirname, '../public/files/protocol-v3.yaml'); @@ -203,6 +208,9 @@ export default withMermaid(defineConfig({ description: "home for everything Lightbug", lang: 'en-GB', cleanUrls: true, + buildEnd(siteConfig) { + expandedProtocol.writeExpandedProtocol(siteConfig.outDir, protocolYamlPath); + }, sitemap: { hostname: process.env.DEPLOYMENT_NAME === 'Production' ? 'https://docs.lightbug.io' : 'https://docs-next.lightbug.io' }, @@ -223,6 +231,7 @@ export default withMermaid(defineConfig({ noExternal: ["vuetify", "vitepress-openapi"] }, plugins: [ + expandedProtocolPlugin(protocolYamlPath, base), // Keep the native samples export available on versions that omit it. { name: 'prototype-native-code-samples-export', diff --git a/.vitepress/plugins/expanded-protocol.cjs b/.vitepress/plugins/expanded-protocol.cjs new file mode 100644 index 000000000..687db5fe6 --- /dev/null +++ b/.vitepress/plugins/expanded-protocol.cjs @@ -0,0 +1,23 @@ +const { readExpandedProtocol, expandedProtocolFilename } = require('../../utils/expanded-protocol.cjs'); + +// Production uses VitePress's buildEnd hook. Serve the same export directly +// from the canonical source in development, without an intermediate file. +module.exports = function expandedProtocolPlugin(sourcePath, base = '/') { + const downloadPath = `${base.replace(/\/$/, '')}/files/${expandedProtocolFilename}`; + return { + name: 'expanded-protocol-download', + configureServer(server) { + server.middlewares.use((request, response, next) => { + if (!['GET', 'HEAD'].includes(request.method) || request.url?.split('?')[0] !== downloadPath) return next(); + try { + const source = readExpandedProtocol(sourcePath); + response.setHeader('Content-Type', 'application/yaml; charset=utf-8'); + response.setHeader('Cache-Control', 'no-cache'); + response.end(request.method === 'HEAD' ? undefined : source); + } catch (error) { + next(error); + } + }); + }, + }; +}; diff --git a/README.md b/README.md index 1c98426e5..5f3300b42 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,61 @@ Both scripts use `cross-env` so they work cross-platform. PR preview workflows and administrator setup: [.github/preview](https://github.com/lightbug-io/docs/blob/main/.github/preview/README.md). +## Protocol YAML authoring and export + +`public/files/protocol-v3.yaml` is the canonical source. It uses native YAML +anchors (`&name`), aliases (`*name`) and merge keys (`<<: *name`), parsed by the +same `js-yaml` dependency used by the docs. There is no separate template engine. +Consumers without merge-key support can use the expanded export below. + +- Definitions used only within one message are anchored at their first use in + that message. Use message-specific anchor names: anchors have document scope, + not message scope, and must appear before their aliases. +- Only header maps shared across messages live in the top-level + `templates.headers` registry: `optionalOkReply`, `correlatedOkAck`, and + `optionalCorrelationAck`. An anchor has no effect unless explicitly aliased + or merged into an actual message definition. +- A YAML merge is shallow. An explicit key replaces that entire merged value; + replacing a header entry does not inherit the entry's other properties. + Anchor smaller maps when individual nested values need to be reused. + +### Navigate shared definitions + +In VS Code with [Red Hat YAML](https://github.com/redhat-developer/vscode-yaml), +put the caret on an alias (`*name`) and run **Go to Definition** from the context +menu. The extension's language server +[resolves aliases to their anchors](https://github.com/redhat-developer/yaml-language-server/blob/main/src/languageservice/services/yamlDefinition.ts). +This follows the explicit alias, not an inherited field name or arbitrary string. + +[IntelliJ IDEA's YAML support](https://www.jetbrains.com/help/idea/yaml.html) +documents alias-to-anchor navigation, anchor usages, and anchor/alias rename. +Use **Go to Declaration or Usages**; the shortcut depends on your key bindings. +These are editor features, not something the docs site adds. If your editor or +extension version lacks them, search for `&name` in the canonical file. The +expanded download below is useful for inspecting all values without jumping. + +### Export expanded YAML + +The protocol overview offers **Download expanded YAML** at +`files/protocol-v3-expanded.yaml`, including on PR previews. The build creates it +from the canonical source; the development server generates it on each request. +Do not commit or edit a second generated specification. + +To inspect or save the same output locally after installing dependencies: + +```bash +npm run --silent export:protocol +npm run --silent export:protocol > /tmp/protocol-v3-expanded.yaml +``` + +The export resolves aliases and merge keys using the `yaml` library's typed +maps, keeping numeric keys as integers and deliberately quoted keys as strings +for SDK generator compatibility. It emits no anchors and removes only +the top-level authoring-only `templates` registry. All other parsed data is +preserved, including sentinels and version overrides. It does not invent runtime +defaults or flatten message-version description inheritance. Comments and +source formatting are not retained. Edit the canonical source and re-export. + ## Protocol sentinel values Numeric field definitions in `public/files/protocol-v3.yaml` can declare raw diff --git a/components/Protocol/DocumentationText.vue b/components/Protocol/DocumentationText.vue index ed35eae3e..a2dbe73c5 100644 --- a/components/Protocol/DocumentationText.vue +++ b/components/Protocol/DocumentationText.vue @@ -1,12 +1,13 @@ diff --git a/components/Protocol/StructuredMessagePage.vue b/components/Protocol/StructuredMessagePage.vue index b54b6adbd..d98b868d9 100644 --- a/components/Protocol/StructuredMessagePage.vue +++ b/components/Protocol/StructuredMessagePage.vue @@ -2,6 +2,7 @@ import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue' import { useRouter, withBase } from 'vitepress' import Message from './Message.vue' +import ExamplesSection from './ExamplesSection.vue' import DocumentationText from './DocumentationText.vue' import SentinelValues from './SentinelValues.vue' import { @@ -22,6 +23,7 @@ import { getDocumentationFormat, getMessageDocumentation, getOperationVariant, + resolveDocumentationErrors, resolveDocumentationFields, type DocumentationOperation, } from '../../utils/MessageDocumentation' @@ -32,7 +34,7 @@ const props = defineProps<{ }>() const message = computed(() => props.yamlData.messages?.[props.messageId]) -const documentation = computed(() => getMessageDocumentation(message.value)) +const documentation = computed(() => getMessageDocumentation(message.value, props.yamlData)) const copyStatus = ref('') const router = useRouter() let removeRouteCorrection: (() => void) | undefined @@ -43,7 +45,7 @@ let activeFrame = 0 const exampleColumns = ref([]) const jumpBarHeight = ref(64) let jumpBarObserver: ResizeObserver | undefined -const operationAnchor = (item: DocumentationOperation) => `message-${props.messageId}-operation-${item.id}` +const operationAnchor = (item: DocumentationOperation) => `message-${props.messageId}-operation-${item.anchorId || item.id}` const acknowledgmentUrl = withBase('/devices/api/messages/5-ack#header') const responseReferenceUrl = withBase('/devices/api/protocol/responses') const panels = computed(() => (documentation.value?.operations || []).flatMap(item => { @@ -70,14 +72,17 @@ const panels = computed(() => (documentation.value?.operations || []).flatMap(it examplesTitle: `${label} examples`, title: role === 'request' ? 'Request' : role === 'response' ? `Expected response${view[role] ? ` (MT${contextId}${contextId === 5 ? ' - ACK' : ''})` : ''}` - : `${item.method ? 'Later publication' : 'Device upload'}${view[role] ? ` (MT${contextId})` : ''}`, + : `${item.method ? 'Later publication' : 'Device upload'}${view[role] ? ` (MT${contextId})` : ''}`, subtitle: role !== 'request' && contextId !== 5 && !!item.method ? usage.title?.replace(/\s*\(MT\d+\)$/, '') : undefined, description: usage.description, acknowledgment: usage.messageId === 5, referenceAnchors: usage.messageId === 5 ? (['headers', 'fields'] as const).flatMap(kind => Object.keys(usage[kind] || {}).map(id => `${anchor}-${role}-${kind}-${id}`)) - // Preserve field deep links when a shortened input list omits them. - : [...sharedHeaders.map(id => `${anchor}-${role}-headers-${id}`), ...Object.keys((usage.messageId === undefined ? message.value : props.yamlData.messages?.[usage.messageId])?.data || {}) + // Preserve header and field deep links when a shortened input list omits them. + : [...sharedHeaders.map(id => `${anchor}-${role}-headers-${id}`), + ...Object.keys(props.yamlData.header || {}).filter(id => !Object.prototype.hasOwnProperty.call(usage.headers || {}, id)) + .map(id => `${anchor}-${role}-headers-${id}`), + ...Object.keys((usage.messageId === undefined ? message.value : props.yamlData.messages?.[usage.messageId])?.data || {}) .filter(id => !Object.prototype.hasOwnProperty.call(usage.fields || {}, id)) .map(id => `${anchor}-${role}-fields-${id}`)], groups: usage.messageId === 5 ? [] : (['headers', 'fields'] as const).map(kind => ({ @@ -101,7 +106,7 @@ const panels = computed(() => (documentation.value?.operations || []).flatMap(it ...context, examplesAnchor: `${anchor}${context.role === (contexts.find(item => item.examples.length)?.role || contexts[0]?.role) ? '' : `-${context.role}`}-examples`, })), - errors: (view.errors || []).map(error => ({ ...error, name: props.yamlData.header?.[4]?.values?.[error.code]?.name })), + errors: resolveDocumentationErrors(props.yamlData, view.errors), } }) })) @@ -183,6 +188,7 @@ const outlineEntries = computed(() => { entries.push({ id: panel.anchor, title: panel.operation.method || 'Upload', depth }) } } + if (message.value.examples?.length) entries.push({ id: `message-${props.messageId}-wire-examples`, title: 'Wire examples', depth: 0 }) entries.push({ id: `message-${props.messageId}-constants`, title: 'Constants', depth: 0 }) return entries }) @@ -321,13 +327,20 @@ onBeforeUnmount(() => {
-

{{ documentation.summary }}

+

+

Documented Method (5) values {{ documentation.methods.join(', ') }}

Applies to {{ documentation.target }}

+

+ Shared optional header · Message ID (1) + can identify a request, response or publication. A response's own ID is separate from + Response To (3). + Message ID and reply rules apply unless an interaction states an exception. +

{{ note.title }}

-

{{ note.description }}

+

@@ -358,7 +371,8 @@ onBeforeUnmount(() => { {{ field.name }}Field {{ field.id }} {{ field.type }} -

+

+

Minimum {{ field.minBytes }} bytes

Maximum {{ field.maxBytes }} bytes

  • {{ value.value }} · {{ value.name }}: {{ value.description }}
  • @@ -379,6 +393,7 @@ onBeforeUnmount(() => {
    +
    @@ -393,8 +408,8 @@ onBeforeUnmount(() => { {{ panel.operation.title }} -

    {{ panel.operation.description }}

    -

    {{ panel.variant.description }}

    +

    +

    Target {{ panel.target }}

    @@ -405,7 +420,8 @@ onBeforeUnmount(() => { {{ context.title }}

    {{ context.subtitle }}

    -

    {{ context.description }}

    +

    +

    Shared optional Message ID and reply rules

    Correlation, status and acknowledgment rules

    {{ group.title }} @@ -424,10 +440,11 @@ onBeforeUnmount(() => {

    Value {{ field.value }} · {{ field.valueName }}

    -

    +

    • {{ value.value }} · {{ value.name }}: {{ value.description }} @@ -440,18 +457,18 @@ onBeforeUnmount(() => {
    Unsuccessful replies -

    Operation-specific causes. Codes are values of Status header 4, not payload fields.

    +

    Applicable errors and operation-specific causes. Codes are values of Status header 4, not payload fields.

    {{ error.code }} {{ error.name }}
    -
    {{ error.description }}
    +