Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

docs: Allow partial variables to be optional (#46585)

Chris Chinchilla04501d2f85af
diff --git a/apps/docs/features/directives/Partial.test.ts b/apps/docs/features/directives/Partial.test.ts
index 5217554a15c..9e0124ddc6e 100644
--- a/apps/docs/features/directives/Partial.test.ts
+++ b/apps/docs/features/directives/Partial.test.ts
@@ -1,7 +1,6 @@
-import { describe, it, expect } from 'vitest'
-
import { mdxToMarkdown } from 'mdast-util-mdx'
import { toMarkdown } from 'mdast-util-to-markdown'
+import { describe, expect, it } from 'vitest'
import { partialsRemark } from './Partial'
import { fromDocsMarkdown } from './utils.server'
@@ -116,7 +115,12 @@ Some more text.
await expect(partialsRemark()(mdast)).rejects.toThrowError(/valid JSON/)
})
- it('should error when required variable is missing', async () => {
+ it('should render an unprovided variable as an empty string', async () => {
+ // The variables.mdx fixture reads "Here is a partial that takes a {{ .var }}."
+ // When `var` is not provided, the `{{ .var }}` placeholder is replaced with
+ // an empty string rather than throwing. The trailing " ." in the expected
+ // output is the intended result: the placeholder is gone, leaving nothing
+ // between "a" and the period.
const markdown = `
# Embed partial
@@ -126,54 +130,64 @@ Some more text.
`.trim()
const mdast = fromDocsMarkdown(markdown)
- await expect(partialsRemark()(mdast)).rejects.toThrowError(
- /Missing required variable in \$Partial ".*variables\.mdx": "var"/
- )
- })
+ const transformed = await partialsRemark()(mdast)
+ const output = toMarkdown(transformed, { extensions: [mdxToMarkdown()] })
- it('should error when unexpected variable is provided', async () => {
- const markdown = `
+ // Note the empty gap where `{{ .var }}` used to be — this is deliberate.
+ const expected = `
# Embed partial
-<$Partial path="/_fixtures/variables.mdx" variables={{ "var": "correct", "extra": "unexpected" }} />
+Here is a partial that takes a .
Some more text.
-`.trim()
+`.trimStart()
- const mdast = fromDocsMarkdown(markdown)
- await expect(partialsRemark()(mdast)).rejects.toThrowError(
- /Unexpected variable in \$Partial ".*variables\.mdx": "extra"/
- )
+ expect(output).toEqual(expected)
+ // The placeholder must be fully removed, not left as literal `{{ .var }}`.
+ expect(output).not.toContain('{{')
})
- it('should error with detailed message for multiple missing variables', async () => {
+ it('should ignore a variable that is not referenced in the partial', async () => {
+ // The variables.mdx fixture only references `var`. Providing an additional
+ // `extra` variable that the partial never uses is silently ignored rather
+ // than throwing — `var` is substituted and `extra` leaves no trace.
const markdown = `
# Embed partial
-<$Partial path="/_fixtures/multiple-variables.mdx" variables={{ "var1": "value1" }} />
+<$Partial path="/_fixtures/variables.mdx" variables={{ "var": "correct", "extra": "unused" }} />
Some more text.
`.trim()
const mdast = fromDocsMarkdown(markdown)
- await expect(partialsRemark()(mdast)).rejects.toThrowError(
- /Missing required variables.*"var2".*"var3".*Expected variables.*"var1".*"var2".*"var3".*Provided variable: "var1"/s
- )
+ const transformed = await partialsRemark()(mdast)
+ const output = toMarkdown(transformed, { extensions: [mdxToMarkdown()] })
+
+ expect(output).toContain('Here is a partial that takes a correct.')
+ expect(output).not.toContain('unused')
})
- it('should error with detailed message for multiple unexpected variables', async () => {
+ it('should render only the unprovided variables as empty when some are provided', async () => {
+ // The multiple-variables.mdx fixture reads:
+ // "This partial has {{ .var1 }}, {{ .var2 }}, and {{ .var3 }}."
+ // Only `var1` is provided here, so `var2` and `var3` collapse to empty
+ // strings while `var1` is substituted normally.
const markdown = `
# Embed partial
-<$Partial path="/_fixtures/variables.mdx" variables={{ "var": "correct", "extra1": "wrong", "extra2": "also wrong" }} />
+<$Partial path="/_fixtures/multiple-variables.mdx" variables={{ "var1": "value1" }} />
Some more text.
`.trim()
const mdast = fromDocsMarkdown(markdown)
- await expect(partialsRemark()(mdast)).rejects.toThrowError(
- /Unexpected variables.*"extra1".*"extra2".*Expected variable: "var".*Provided variables.*"var".*"extra1".*"extra2"/s
- )
+ const transformed = await partialsRemark()(mdast)
+ const output = toMarkdown(transformed, { extensions: [mdxToMarkdown()] })
+
+ // Provided variable is substituted; the two unprovided ones leave empty gaps.
+ expect(output).toContain('This partial has value1, , and .')
+ // No placeholder text survives for the unprovided variables.
+ expect(output).not.toContain('{{')
})
it('should succeed when all variables match exactly', async () => {
@@ -212,7 +226,12 @@ Some more text.
expect(output).toContain('alphanumeric value')
})
- it('should error when hyphenated variable is missing', async () => {
+ it('should render unprovided hyphenated variables as empty', async () => {
+ // The hyphenated-variables.mdx fixture reads:
+ // "This partial has {{ .my-var }}, {{ .another_var }}, and {{ .myVar123 }}."
+ // Only `my-var` is provided, so the underscore and alphanumeric variables
+ // collapse to empty strings — confirming the empty-substitution behavior
+ // applies to all supported variable name styles.
const markdown = `
# Embed partial
@@ -222,8 +241,10 @@ Some more text.
`.trim()
const mdast = fromDocsMarkdown(markdown)
- await expect(partialsRemark()(mdast)).rejects.toThrowError(
- /Missing required variables.*"another_var".*"myVar123".*Expected variables.*"my-var".*"another_var".*"myVar123".*Provided variable: "my-var"/s
- )
+ const transformed = await partialsRemark()(mdast)
+ const output = toMarkdown(transformed, { extensions: [mdxToMarkdown()] })
+
+ expect(output).toContain('This partial has value, , and .')
+ expect(output).not.toContain('{{')
})
})
diff --git a/apps/docs/features/directives/Partial.ts b/apps/docs/features/directives/Partial.ts
index 15d40004f54..86001a7ade8 100644
--- a/apps/docs/features/directives/Partial.ts
+++ b/apps/docs/features/directives/Partial.ts
@@ -7,6 +7,10 @@
* Simple string replacement is supported. The replacement strings are
* specified using the `variables` field.
*
+ * Variable substitution is optional. Any variable referenced in the partial
+ * content but not provided is rendered as an empty string, and any variable
+ * provided but not referenced in the content is ignored.
+ *
* ## Examples
*
* ### Simple partial
@@ -33,14 +37,14 @@
* ```
*/
-import { type Root } from 'mdast'
-import type { MdxJsxFlowElement } from 'mdast-util-mdx-jsx'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
+import { PARTIALS_DIRECTORY } from '~/lib/docs'
+import { type Root } from 'mdast'
+import type { MdxJsxFlowElement } from 'mdast-util-mdx-jsx'
import { type Parent } from 'unist'
import { visitParents } from 'unist-util-visit-parents'
-import { PARTIALS_DIRECTORY } from '~/lib/docs'
import { fromDocsMarkdown, getAttributeValue, getAttributeValueExpression } from './utils.server'
export function partialsRemark() {
@@ -74,67 +78,19 @@ function toFilePath(node: MdxJsxFlowElement) {
}
/**
- * Extracts all variable names expected in the partial content.
- * Returns a Set of variable names found in {{ .variableName }} patterns.
- * Variable names can contain alphanumeric characters, hyphens, and underscores.
- */
-function extractExpectedVariables(content: string): Set<string> {
- const variablePattern = /(?<!\\)\{\{\s*\.([\w-]+)\s*\}\}/g
- const variables = new Set<string>()
- let match
-
- while ((match = variablePattern.exec(content)) !== null) {
- variables.add(match[1])
- }
-
- return variables
-}
-
-/**
- * Validates that all expected variables are provided and no unexpected variables are included.
- * Throws descriptive errors if validation fails.
+ * Substitutes provided variables into the partial content. Variable
+ * substitution is optional: any variable referenced in the content but not
+ * provided is replaced with an empty string, and any variable provided but not
+ * referenced is ignored. The leading `\` escape (`\{{ .var }}`) opts a
+ * placeholder out of substitution.
*/
-function validateVariables(
- content: string,
- vars: Record<string, string> | undefined,
- partialPath: string
-) {
- const expectedVars = extractExpectedVariables(content)
- const providedVars = vars ? new Set(Object.keys(vars)) : new Set<string>()
-
- // Check for missing variables
- const missingVars = [...expectedVars].filter((v) => !providedVars.has(v))
- if (missingVars.length > 0) {
- const varList = missingVars.map((v) => `"${v}"`).join(', ')
- const plural = missingVars.length > 1
- throw new Error(
- `Missing required variable${plural ? 's' : ''} in $Partial "${partialPath}": ${varList}\n` +
- `Expected variable${expectedVars.size > 1 ? 's' : ''}: ${[...expectedVars].map((v) => `"${v}"`).join(', ')}\n` +
- `Provided variable${providedVars.size !== 1 ? 's' : ''}: ${providedVars.size > 0 ? [...providedVars].map((v) => `"${v}"`).join(', ') : 'none'}`
- )
- }
-
- // Check for unexpected variables
- const unexpectedVars = [...providedVars].filter((v) => !expectedVars.has(v))
- if (unexpectedVars.length > 0) {
- const varList = unexpectedVars.map((v) => `"${v}"`).join(', ')
- const plural = unexpectedVars.length > 1
- throw new Error(
- `Unexpected variable${plural ? 's' : ''} in $Partial "${partialPath}": ${varList}\n` +
- `Expected variable${expectedVars.size !== 1 ? 's' : ''}: ${expectedVars.size > 0 ? [...expectedVars].map((v) => `"${v}"`).join(', ') : 'none'}\n` +
- `Provided variable${plural ? 's' : ''}: ${[...providedVars].map((v) => `"${v}"`).join(', ')}`
- )
- }
-}
-
function substituteVars(content: string, vars: Record<string, string> | undefined) {
- if (vars === undefined) {
- return content
- }
-
- for (const [key, value] of Object.entries(vars)) {
+ for (const [key, value] of Object.entries(vars ?? {})) {
content = content.replace(new RegExp(`(?<!\\\\)\\{\\{\\s*\\.${key}\\s*\\}\\}`, 'g'), value)
}
+
+ // Clear any remaining (unprovided) placeholders.
+ content = content.replace(/(?<!\\)\{\{\s*\.[\w-]+\s*\}\}/g, '')
return content
}
@@ -159,12 +115,7 @@ function getVariables(node: MdxJsxFlowElement): undefined | Record<string, strin
async function fetchPartialsContent(tree: Root) {
// INVARIANT: These must be pushed to in the same order because the index is // used to keep track of the relationship.
- const partialNodes = [] as [
- Parent,
- MdxJsxFlowElement,
- undefined | Record<string, string>,
- string,
- ][]
+ const partialNodes = [] as [Parent, MdxJsxFlowElement, undefined | Record<string, string>][]
const pendingFetches = [] as Promise<string>[]
visitParents(tree, 'mdxJsxFlowElement', (node: MdxJsxFlowElement, ancestors) => {
@@ -174,9 +125,8 @@ async function fetchPartialsContent(tree: Root) {
const filePath = toFilePath(node)
const variables = getVariables(node)
const fetchTask = readFile(filePath, 'utf-8')
- const partialPath = getAttributeValue(node, 'path') as string
- partialNodes.push([parent, node, variables, partialPath])
+ partialNodes.push([parent, node, variables])
pendingFetches.push(fetchTask)
})
@@ -184,21 +134,19 @@ async function fetchPartialsContent(tree: Root) {
const nodeContentMap = new Map<
MdxJsxFlowElement,
- [Parent, string, undefined | Record<string, string>, string]
+ [Parent, string, undefined | Record<string, string>]
>()
- partialNodes.forEach(([parent, node, variables, partialPath], index) => {
- nodeContentMap.set(node, [parent, resolvedContent[index], variables, partialPath])
+ partialNodes.forEach(([parent, node, variables], index) => {
+ nodeContentMap.set(node, [parent, resolvedContent[index], variables])
})
return nodeContentMap
}
function rewriteNodes(
- contentMap: Map<MdxJsxFlowElement, [Parent, string, undefined | Record<string, string>, string]>
+ contentMap: Map<MdxJsxFlowElement, [Parent, string, undefined | Record<string, string>]>
) {
- for (const [node, [parent, rawContent, vars, partialPath]] of contentMap) {
- const trimmedContent = rawContent.trim()
- validateVariables(trimmedContent, vars, partialPath)
- let content = substituteVars(trimmedContent, vars)
+ for (const [node, [parent, rawContent, vars]] of contentMap) {
+ const content = substituteVars(rawContent.trim(), vars)
const replacementContent = fromDocsMarkdown(content)
parent.children.splice(parent.children.indexOf(node), 1, replacementContent)
}