diff --git a/docs/content/2.syntax/2.components.md b/docs/content/2.syntax/2.components.md index d5e9d41ab..a7c6155b1 100644 --- a/docs/content/2.syntax/2.components.md +++ b/docs/content/2.syntax/2.components.md @@ -303,12 +303,31 @@ Nested components can read the enclosing component's resolved props through the :: ``` +### Nested props + +Bindings also work inside object and array props, whether they come from a YAML props block or inline JSON. Prefix the nested key with `:`: + +```mdc +::page-hero +--- +links: + - label: Publish your first mission + :to: data.platform.dashboard_login_url +--- +:: + +::page-hero{:links='[{"label":"Sign in",":to":"data.platform.dashboard_login_url"}]'} +:: +``` + +Both resolve to `links: [{ label: '…', to: '' }]`. + ### Resolution rules - If the `:prefixed` value is a valid JSON literal (for example `5`, `true`, `"foo"`, `{"a":1}`), it's used as-is. - Otherwise, the value is treated as a dot-path and resolved against `{ frontmatter, meta, data, props }`. - Unknown paths resolve to `undefined`: the prop is passed as `undefined` rather than the raw string. -- Only props authored with the `:` prefix participate in data binding. Plain `prop="value"` attributes are always passed as literal strings. +- Only props authored with the `:` prefix participate in data binding, at any depth. Plain `prop="value"` attributes (and un-prefixed nested keys) are always passed as literal values. ::callout{color="info" icon="i-lucide-replace"} Need to interpolate a value directly into text rather than a prop? The [Binding plugin](/plugins/built-in/binding) adds a `{{ path || default }}` inline shorthand that resolves against the same render context. diff --git a/packages/comark/src/internal/stringify/attributes.ts b/packages/comark/src/internal/stringify/attributes.ts index 9c7511b65..b5d29bdd9 100644 --- a/packages/comark/src/internal/stringify/attributes.ts +++ b/packages/comark/src/internal/stringify/attributes.ts @@ -38,6 +38,8 @@ const HTML_SINK_PROPS = new Set(['innerhtml', 'dangerouslysetinnerhtml', 'textco * * With `parseJson: true`, every `:prefixed` string is JSON-parsed first and * the `:` prefix is always stripped, falling back to the dot-path lookup. + * `:prefixed` keys nested inside object/array values (YAML block props, JSON + * props) are resolved the same way, at any depth. * The `$` metadata key is never forwarded. */ export function resolveAttributes( @@ -62,15 +64,16 @@ export function resolveAttributes( // Framework mode: always strip `:` and hand components real JS values. if (typeof value === 'string') { try { - outValue = JSON.parse(value) + outValue = resolveNestedBindings(JSON.parse(value), renderData, options) } catch { // not JSON — fall through to dot-path lookup outValue = get(renderData, value) } } else { // Non-string binding value (e.g. an object literal the parser already - // decoded) — pass through with the prefix stripped. - outValue = value + // decoded) — pass through with the prefix stripped, resolving any + // bindings nested inside it. + outValue = resolveNestedBindings(value, renderData, options) } resultKey = outKey } else if (isBinding && typeof value === 'string') { @@ -82,20 +85,16 @@ export function resolveAttributes( outValue = value } } else { - outValue = value + // Objects/arrays (YAML block props, JSON props) may carry `:key` bindings + // at any depth, e.g. `links: [{ label: …, :to: data.url }]`. + outValue = resolveNestedBindings(value, renderData, options) } // Hard floor: a binding must never resolve href/src to an unsafe scheme // (javascript:, data:text/html, …). Parse-time validation only sees the // literal path, so the resolved value is checked here — even when the // security plugin is not enabled. - const lowerOutKey = outKey.toLowerCase() - if ( - isBinding && - (lowerOutKey === 'href' || lowerOutKey === 'src' || lowerOutKey === 'xlink:href') && - typeof outValue === 'string' && - isUnsafeUrlValue(outValue) - ) { + if (isBinding && isUnsafeUrlBinding(outKey, outValue)) { continue } @@ -104,6 +103,76 @@ export function resolveAttributes( return result } +function isUnsafeUrlBinding(key: string, value: unknown): boolean { + const lowerKey = key.toLowerCase() + return ( + (lowerKey === 'href' || lowerKey === 'src' || lowerKey === 'xlink:href') && + typeof value === 'string' && + isUnsafeUrlValue(value) + ) +} + +/** + * Resolve `:prefixed` keys inside nested objects and arrays, returning a new + * structure only when something changed. Primitives are returned as-is. + */ +function resolveNestedBindings(value: unknown, renderData: NodeRenderData, options: ResolveAttributesOptions): unknown { + if (!value || typeof value !== 'object') return value + + if (Array.isArray(value)) { + let result: unknown[] | undefined + for (let i = 0; i < value.length; i++) { + const item = resolveNestedBindings(value[i], renderData, options) + if (item !== value[i]) { + result ??= value.slice() + result[i] = item + } + } + return result ?? value + } + + const proto = Object.getPrototypeOf(value) + if (proto !== Object.prototype && proto !== null) return value + + const source = value as Record + let result: Record | undefined + for (const key in source) { + const item = source[key] + if (key.charCodeAt(0) !== 58 /* ':' */) { + const resolved = resolveNestedBindings(item, renderData, options) + if (resolved !== item) { + result ??= { ...source } + result[key] = resolved + } + continue + } + + const outKey = key.slice(1) + let outValue: unknown + if (typeof item === 'string') { + if (options.parseJson) { + try { + outValue = resolveNestedBindings(JSON.parse(item), renderData, options) + } catch { + outValue = get(renderData, item) + } + } else { + outValue = get(renderData, item) + // Unresolved paths keep their `:` key, like top-level attributes + if (outValue === undefined) continue + } + } else { + outValue = resolveNestedBindings(item, renderData, options) + } + + result ??= { ...source } + delete result[key] + if (isUnsafeUrlBinding(outKey, outValue)) continue + result[outKey] = outValue + } + return result ?? value +} + /** * Read a named attribute, preferring its `:prefixed` binding (resolved against * `renderData`) over the literal `key`. Falls back to the raw value when the diff --git a/packages/comark/test/resolve-attributes.test.ts b/packages/comark/test/resolve-attributes.test.ts index bab8b0b25..02c5b3378 100644 --- a/packages/comark/test/resolve-attributes.test.ts +++ b/packages/comark/test/resolve-attributes.test.ts @@ -233,6 +233,94 @@ nothing: null }) }) +describe('nested bindings in object/array props (#286)', () => { + const renderData = makeRenderData({ + data: { platform: { dashboard_login_url: 'https://app.example.com/login' } }, + frontmatter: { cta: 'Sign in' }, + }) + + it('resolves :prefixed keys inside YAML block-props arrays (parseJson mode)', async () => { + const doc = await parseMarkdown(`::page-hero +--- +links: + - label: Publish your first mission + :to: data.platform.dashboard_login_url + - :label: frontmatter.cta + to: /static +--- +::`) + const attrs = (doc.nodes[0] as unknown as [string, Record])[1] + + expect(resolveAttributes(attrs, renderData, { parseJson: true })).toEqual({ + links: [ + { label: 'Publish your first mission', to: 'https://app.example.com/login' }, + { label: 'Sign in', to: '/static' }, + ], + }) + }) + + it('resolves :prefixed keys inside inline JSON props', async () => { + const doc = await parseMarkdown( + `::page-hero{:links='[{"label":"Go",":to":"data.platform.dashboard_login_url"}]'}\n::` + ) + const attrs = (doc.nodes[0] as unknown as [string, Record])[1] + + expect(resolveAttributes(attrs, renderData, { parseJson: true })).toEqual({ + links: [{ label: 'Go', to: 'https://app.example.com/login' }], + }) + }) + + it('resolves bindings nested in a JSON string value (parseJson mode)', () => { + const result = resolveAttributes( + { ':links': '[{"label":"Go",":to":"data.platform.dashboard_login_url"}]' }, + renderData, + { parseJson: true } + ) + expect(result).toEqual({ links: [{ label: 'Go', to: 'https://app.example.com/login' }] }) + }) + + it('drops unsafe URL bindings nested in a JSON string value (parseJson mode)', () => { + const result = resolveAttributes( + { ':links': '[{"label":"x",":href":"frontmatter.home"}]' }, + makeRenderData({ frontmatter: { home: 'javascript:alert(1)' } }), + { parseJson: true } + ) + expect(result).toEqual({ links: [{ label: 'x' }] }) + }) + + it('JSON-parses nested literals and resolves deeply nested objects (parseJson mode)', () => { + const result = resolveAttributes( + { ':config': { ':count': '3', inner: { ':url': 'data.platform.dashboard_login_url' } } }, + renderData, + { parseJson: true } + ) + expect(result).toEqual({ config: { count: 3, inner: { url: 'https://app.example.com/login' } } }) + }) + + it('resolves nested paths in preserve mode and keeps unresolved ones verbatim', () => { + const result = resolveAttributes( + { links: [{ ':to': 'data.platform.dashboard_login_url', ':other': 'data.missing' }] }, + renderData + ) + expect(result).toEqual({ links: [{ to: 'https://app.example.com/login', ':other': 'data.missing' }] }) + }) + + it('does not mutate the source attributes', () => { + const attrs = { links: [{ ':to': 'data.platform.dashboard_login_url' }] } + resolveAttributes(attrs, renderData, { parseJson: true }) + expect(attrs).toEqual({ links: [{ ':to': 'data.platform.dashboard_login_url' }] }) + }) + + it('drops nested :href bindings resolving to an unsafe URL', () => { + const result = resolveAttributes( + { links: [{ label: 'x', ':href': 'frontmatter.home' }] }, + makeRenderData({ frontmatter: { home: 'javascript:alert(1)' } }), + { parseJson: true } + ) + expect(result).toEqual({ links: [{ label: 'x' }] }) + }) +}) + describe('resolveAttribute (single-attr lookup)', () => { const renderData = makeRenderData({ frontmatter: { home: 'https://example.com' } }) diff --git a/test/bundle.test.ts b/test/bundle.test.ts index 7d61a1e74..aeb5a8235 100644 --- a/test/bundle.test.ts +++ b/test/bundle.test.ts @@ -67,7 +67,7 @@ describe('package bundle size', { timeout: 60_000 }, () => { "@comark/react": "37.7k (76 files)", "@comark/svelte": "45.7k (84 files)", "@comark/vue": "56.0k (80 files)", - "comark": "374k (160 files)", + "comark": "376k (160 files)", } `) })