payload-markdown 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/README.md +16 -0
  2. package/dist/agent/access.d.ts +1 -1
  3. package/dist/agent/access.js.map +1 -1
  4. package/dist/agent/guide.d.ts +3 -0
  5. package/dist/agent/guide.js +28 -2
  6. package/dist/agent/guide.js.map +1 -1
  7. package/dist/agent/palettes.d.ts +55 -0
  8. package/dist/agent/palettes.js +194 -0
  9. package/dist/agent/palettes.js.map +1 -0
  10. package/dist/agent/skill.d.ts +2 -2
  11. package/dist/agent/skill.js +2 -2
  12. package/dist/agent/skill.js.map +1 -1
  13. package/dist/agent/validate.d.ts +1 -1
  14. package/dist/agent/validate.js +3 -0
  15. package/dist/agent/validate.js.map +1 -1
  16. package/dist/appearance/PaletteRowLabel.client.d.ts +2 -0
  17. package/dist/appearance/PaletteRowLabel.client.js +70 -0
  18. package/dist/appearance/PaletteRowLabel.client.js.map +1 -0
  19. package/dist/appearance/config.d.ts +8 -0
  20. package/dist/appearance/config.js +172 -0
  21. package/dist/appearance/config.js.map +1 -0
  22. package/dist/appearance/options.d.ts +11 -0
  23. package/dist/appearance/options.js +15 -0
  24. package/dist/appearance/options.js.map +1 -0
  25. package/dist/appearance/runtime.d.ts +25 -0
  26. package/dist/appearance/runtime.js +126 -0
  27. package/dist/appearance/runtime.js.map +1 -0
  28. package/dist/components/MarkdownRenderer/Component.js +4 -0
  29. package/dist/components/MarkdownRenderer/Component.js.map +1 -1
  30. package/dist/core/plugins/rehypeResolveIcons.js +10 -1
  31. package/dist/core/plugins/rehypeResolveIcons.js.map +1 -1
  32. package/dist/core/plugins/remarkCompileLayouts.js.map +1 -1
  33. package/dist/core/plugins/remarkDirectiveLines.d.ts +7 -5
  34. package/dist/core/plugins/remarkDirectiveLines.js +29 -18
  35. package/dist/core/plugins/remarkDirectiveLines.js.map +1 -1
  36. package/dist/core/plugins/remarkLayoutDirectives.js +1 -1
  37. package/dist/core/plugins/remarkLayoutDirectives.js.map +1 -1
  38. package/dist/core/plugins/remarkValidateDirectiveThemes.js +7 -14
  39. package/dist/core/plugins/remarkValidateDirectiveThemes.js.map +1 -1
  40. package/dist/core/plugins/remarkValidatePalettes.d.ts +9 -0
  41. package/dist/core/plugins/remarkValidatePalettes.js +51 -0
  42. package/dist/core/plugins/remarkValidatePalettes.js.map +1 -0
  43. package/dist/core/renderMarkdown.js +4 -221
  44. package/dist/core/renderMarkdown.js.map +1 -1
  45. package/dist/core/sanitizeSchema.d.ts +11 -0
  46. package/dist/core/sanitizeSchema.js +176 -0
  47. package/dist/core/sanitizeSchema.js.map +1 -0
  48. package/dist/directive-spec.json +60 -0
  49. package/dist/directives/definitions/badge.d.ts +5 -2
  50. package/dist/directives/definitions/badge.js +138 -10
  51. package/dist/directives/definitions/badge.js.map +1 -1
  52. package/dist/directives/definitions/badges.d.ts +1 -2
  53. package/dist/directives/definitions/badges.js +12 -3
  54. package/dist/directives/definitions/badges.js.map +1 -1
  55. package/dist/directives/definitions/button.d.ts +7 -3
  56. package/dist/directives/definitions/button.js +211 -14
  57. package/dist/directives/definitions/button.js.map +1 -1
  58. package/dist/directives/definitions/buttons.d.ts +1 -2
  59. package/dist/directives/definitions/buttons.js +12 -3
  60. package/dist/directives/definitions/buttons.js.map +1 -1
  61. package/dist/directives/definitions/callout.d.ts +1 -2
  62. package/dist/directives/definitions/callout.js +46 -5
  63. package/dist/directives/definitions/callout.js.map +1 -1
  64. package/dist/directives/definitions/card.d.ts +6 -4
  65. package/dist/directives/definitions/card.js +64 -11
  66. package/dist/directives/definitions/card.js.map +1 -1
  67. package/dist/directives/definitions/cards.d.ts +1 -2
  68. package/dist/directives/definitions/cards.js +49 -4
  69. package/dist/directives/definitions/cards.js.map +1 -1
  70. package/dist/directives/definitions/cell.d.ts +2 -2
  71. package/dist/directives/definitions/cell.js +9 -3
  72. package/dist/directives/definitions/cell.js.map +1 -1
  73. package/dist/directives/definitions/columns.d.ts +3 -4
  74. package/dist/directives/definitions/columns.js +17 -3
  75. package/dist/directives/definitions/columns.js.map +1 -1
  76. package/dist/directives/definitions/details.d.ts +1 -2
  77. package/dist/directives/definitions/details.js +28 -3
  78. package/dist/directives/definitions/details.js.map +1 -1
  79. package/dist/directives/definitions/section.d.ts +1 -2
  80. package/dist/directives/definitions/section.js +26 -3
  81. package/dist/directives/definitions/section.js.map +1 -1
  82. package/dist/directives/definitions/steps.d.ts +1 -2
  83. package/dist/directives/definitions/steps.js +26 -3
  84. package/dist/directives/definitions/steps.js.map +1 -1
  85. package/dist/directives/definitions/tab.d.ts +8 -2
  86. package/dist/directives/definitions/tab.js +45 -3
  87. package/dist/directives/definitions/tab.js.map +1 -1
  88. package/dist/directives/definitions/tabs.d.ts +1 -1
  89. package/dist/directives/definitions/tabs.js +44 -3
  90. package/dist/directives/definitions/tabs.js.map +1 -1
  91. package/dist/directives/definitions/toc.d.ts +1 -2
  92. package/dist/directives/definitions/toc.js +33 -5
  93. package/dist/directives/definitions/toc.js.map +1 -1
  94. package/dist/directives/diagnostics.d.ts +2 -10
  95. package/dist/directives/diagnostics.js +27 -141
  96. package/dist/directives/diagnostics.js.map +1 -1
  97. package/dist/directives/iconPlaceholder.d.ts +9 -3
  98. package/dist/directives/iconPlaceholder.js +8 -1
  99. package/dist/directives/iconPlaceholder.js.map +1 -1
  100. package/dist/directives/lint.d.ts +11 -0
  101. package/dist/directives/lint.js +33 -0
  102. package/dist/directives/lint.js.map +1 -0
  103. package/dist/directives/palette.d.ts +23 -0
  104. package/dist/directives/palette.js +40 -0
  105. package/dist/directives/palette.js.map +1 -0
  106. package/dist/directives/registry.d.ts +23 -5
  107. package/dist/directives/registry.js +52 -40
  108. package/dist/directives/registry.js.map +1 -1
  109. package/dist/directives/spec.d.ts +6 -2
  110. package/dist/directives/spec.js +29 -50
  111. package/dist/directives/spec.js.map +1 -1
  112. package/dist/directives/themeDiagnostics.d.ts +8 -0
  113. package/dist/directives/themeDiagnostics.js +21 -0
  114. package/dist/directives/themeDiagnostics.js.map +1 -0
  115. package/dist/directives/types.d.ts +157 -14
  116. package/dist/directives/types.js +6 -1
  117. package/dist/directives/types.js.map +1 -1
  118. package/dist/editor/directiveConfig.d.ts +15 -1
  119. package/dist/editor/directiveConfig.js +21 -1
  120. package/dist/editor/directiveConfig.js.map +1 -1
  121. package/dist/editor/directives/completions.d.ts +4 -2
  122. package/dist/editor/directives/completions.js +33 -7
  123. package/dist/editor/directives/completions.js.map +1 -1
  124. package/dist/editor/directives/diagnostics.d.ts +2 -2
  125. package/dist/editor/directives/diagnostics.js +10 -3
  126. package/dist/editor/directives/diagnostics.js.map +1 -1
  127. package/dist/editor/themes/payload.js +2 -1
  128. package/dist/editor/themes/payload.js.map +1 -1
  129. package/dist/exports/client.d.ts +4 -1
  130. package/dist/exports/client.js +5 -2
  131. package/dist/exports/client.js.map +1 -1
  132. package/dist/field/MarkdownField/Component.js +54 -3
  133. package/dist/field/MarkdownField/Component.js.map +1 -1
  134. package/dist/icons/entries.d.ts +22 -0
  135. package/dist/icons/entries.js +50 -0
  136. package/dist/icons/entries.js.map +1 -0
  137. package/dist/icons/resolve.d.ts +2 -1
  138. package/dist/icons/resolve.js +2 -2
  139. package/dist/icons/resolve.js.map +1 -1
  140. package/dist/icons/sanitizeSvg.d.ts +12 -2
  141. package/dist/icons/sanitizeSvg.js +104 -3
  142. package/dist/icons/sanitizeSvg.js.map +1 -1
  143. package/dist/index.d.ts +11 -4
  144. package/dist/index.js +34 -3
  145. package/dist/index.js.map +1 -1
  146. package/dist/mcp/index.d.ts +2 -2
  147. package/dist/mcp/index.js +65 -4
  148. package/dist/mcp/index.js.map +1 -1
  149. package/dist/palettes/colors.d.ts +21 -0
  150. package/dist/palettes/colors.js +43 -0
  151. package/dist/palettes/colors.js.map +1 -0
  152. package/dist/palettes/contrast.d.ts +7 -0
  153. package/dist/palettes/contrast.js +63 -0
  154. package/dist/palettes/contrast.js.map +1 -0
  155. package/dist/palettes/defaults.d.ts +8 -0
  156. package/dist/palettes/defaults.js +275 -0
  157. package/dist/palettes/defaults.js.map +1 -0
  158. package/dist/palettes/diagnostics.d.ts +10 -0
  159. package/dist/palettes/diagnostics.js +38 -0
  160. package/dist/palettes/diagnostics.js.map +1 -0
  161. package/dist/palettes/index.d.ts +61 -0
  162. package/dist/palettes/index.js +246 -0
  163. package/dist/palettes/index.js.map +1 -0
  164. package/dist/render/renderMarkdown.d.ts +3 -1
  165. package/dist/render/renderMarkdown.js +9 -1
  166. package/dist/render/renderMarkdown.js.map +1 -1
  167. package/dist/runtime/index.d.ts +12 -1
  168. package/dist/runtime/index.js +21 -2
  169. package/dist/runtime/index.js.map +1 -1
  170. package/dist/types/core.d.ts +43 -0
  171. package/dist/types/core.js.map +1 -1
  172. package/dist/types.d.ts +46 -2
  173. package/dist/types.js.map +1 -1
  174. package/dist/version.d.ts +1 -1
  175. package/dist/version.js +1 -1
  176. package/dist/version.js.map +1 -1
  177. package/package.json +1 -1
  178. package/skills/payload-markdown/claude/SKILL.md +1 -0
  179. package/skills/payload-markdown/claude/reference/directive-spec.json +60 -0
  180. package/skills/payload-markdown/claude/reference/mcp-content-workflow.md +7 -0
  181. package/skills/payload-markdown/claude/reference/payload-markdown-directives.md +22 -2
  182. package/skills/payload-markdown/claude/skill.json +2 -2
  183. package/skills/payload-markdown/codex/SKILL.md +1 -0
  184. package/skills/payload-markdown/codex/reference/directive-spec.json +60 -0
  185. package/skills/payload-markdown/codex/reference/mcp-content-workflow.md +7 -0
  186. package/skills/payload-markdown/codex/reference/payload-markdown-directives.md +22 -2
  187. package/skills/payload-markdown/codex/skill.json +2 -2
  188. package/dist/core/plugins/directiveBadge.d.ts +0 -6
  189. package/dist/core/plugins/directiveBadge.js +0 -94
  190. package/dist/core/plugins/directiveBadge.js.map +0 -1
  191. package/dist/core/plugins/directiveButton.d.ts +0 -6
  192. package/dist/core/plugins/directiveButton.js +0 -115
  193. package/dist/core/plugins/directiveButton.js.map +0 -1
  194. package/dist/directives/buttonSyntax.d.ts +0 -7
  195. package/dist/directives/buttonSyntax.js +0 -6
  196. package/dist/directives/buttonSyntax.js.map +0 -1
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The `icon` attribute: one icon or a comma-separated list. Each entry is an
3
+ * icon ref, optionally followed by space-separated `key=value` options that
4
+ * belong to that icon alone:
5
+ *
6
+ * icon="@fa-brands/debian palette=debian, @fa-brands/ubuntu palette=ubuntu"
7
+ *
8
+ * Options travel with their icon, so reordering the list never swaps colours,
9
+ * and the same icon can appear twice with different palettes.
10
+ */
11
+ export type IconEntry = {
12
+ /** Palette name for this icon only. */
13
+ palette?: string;
14
+ /** The `@pack/name` icon reference. */
15
+ ref: string;
16
+ };
17
+ export type ParsedIconEntries = {
18
+ entries: IconEntry[];
19
+ warnings: string[];
20
+ };
21
+ export declare function parseIconEntries(value: string | undefined): ParsedIconEntries;
22
+ export declare function getExtraIconWarnings(directive: string, entries: IconEntry[]): string[];
@@ -0,0 +1,50 @@
1
+ /**
2
+ * The `icon` attribute: one icon or a comma-separated list. Each entry is an
3
+ * icon ref, optionally followed by space-separated `key=value` options that
4
+ * belong to that icon alone:
5
+ *
6
+ * icon="@fa-brands/debian palette=debian, @fa-brands/ubuntu palette=ubuntu"
7
+ *
8
+ * Options travel with their icon, so reordering the list never swaps colours,
9
+ * and the same icon can appear twice with different palettes.
10
+ */ const ICON_ENTRY_OPTIONS = [
11
+ 'palette'
12
+ ];
13
+ export function parseIconEntries(value) {
14
+ const entries = [];
15
+ const warnings = [];
16
+ for (const raw of value?.split(',') ?? []){
17
+ const [ref, ...options] = raw.trim().split(/\s+/).filter(Boolean);
18
+ if (!ref) continue;
19
+ const entry = {
20
+ ref
21
+ };
22
+ for (const option of options){
23
+ const separator = option.indexOf('=');
24
+ const key = separator > 0 ? option.slice(0, separator) : '';
25
+ const optionValue = separator > 0 ? option.slice(separator + 1).replace(/^["']|["']$/g, '') : '';
26
+ if (!ICON_ENTRY_OPTIONS.includes(key) || !optionValue) {
27
+ warnings.push(`Unknown icon option "${option}" on "${ref}". Write options as key=value; supported: ${ICON_ENTRY_OPTIONS.join(', ')}.`);
28
+ continue;
29
+ }
30
+ entry.palette = optionValue;
31
+ }
32
+ entries.push(entry);
33
+ }
34
+ return {
35
+ entries,
36
+ warnings
37
+ };
38
+ }
39
+ /** Directives that show a single icon: extra entries of an `icon` list are reported. */ const SINGLE_ICON_DIRECTIVES = new Set([
40
+ 'button',
41
+ 'callout'
42
+ ]);
43
+ export function getExtraIconWarnings(directive, entries) {
44
+ if (!SINGLE_ICON_DIRECTIVES.has(directive) || entries.length < 2) return [];
45
+ return [
46
+ `"${directive}" shows one icon; ${entries.slice(1).map((entry)=>`"${entry.ref}"`).join(', ')} ${entries.length > 2 ? 'are' : 'is'} ignored. Only cards show a list of icons.`
47
+ ];
48
+ }
49
+
50
+ //# sourceMappingURL=entries.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/icons/entries.ts"],"sourcesContent":["/**\n * The `icon` attribute: one icon or a comma-separated list. Each entry is an\n * icon ref, optionally followed by space-separated `key=value` options that\n * belong to that icon alone:\n *\n * icon=\"@fa-brands/debian palette=debian, @fa-brands/ubuntu palette=ubuntu\"\n *\n * Options travel with their icon, so reordering the list never swaps colours,\n * and the same icon can appear twice with different palettes.\n */\n\nexport type IconEntry = {\n /** Palette name for this icon only. */\n palette?: string\n /** The `@pack/name` icon reference. */\n ref: string\n}\n\nexport type ParsedIconEntries = {\n entries: IconEntry[]\n warnings: string[]\n}\n\nconst ICON_ENTRY_OPTIONS = ['palette'] as const\n\nexport function parseIconEntries(value: string | undefined): ParsedIconEntries {\n const entries: IconEntry[] = []\n const warnings: string[] = []\n\n for (const raw of value?.split(',') ?? []) {\n const [ref, ...options] = raw.trim().split(/\\s+/).filter(Boolean)\n if (!ref) continue\n\n const entry: IconEntry = { ref }\n\n for (const option of options) {\n const separator = option.indexOf('=')\n const key = separator > 0 ? option.slice(0, separator) : ''\n const optionValue = separator > 0 ? option.slice(separator + 1).replace(/^[\"']|[\"']$/g, '') : ''\n\n if (!(ICON_ENTRY_OPTIONS as readonly string[]).includes(key) || !optionValue) {\n warnings.push(\n `Unknown icon option \"${option}\" on \"${ref}\". Write options as key=value; supported: ${ICON_ENTRY_OPTIONS.join(', ')}.`,\n )\n continue\n }\n\n entry.palette = optionValue\n }\n\n entries.push(entry)\n }\n\n return { entries, warnings }\n}\n\n/** Directives that show a single icon: extra entries of an `icon` list are reported. */\nconst SINGLE_ICON_DIRECTIVES = new Set(['button', 'callout'])\n\nexport function getExtraIconWarnings(directive: string, entries: IconEntry[]): string[] {\n if (!SINGLE_ICON_DIRECTIVES.has(directive) || entries.length < 2) return []\n\n return [\n `\"${directive}\" shows one icon; ${entries\n .slice(1)\n .map((entry) => `\"${entry.ref}\"`)\n .join(', ')} ${entries.length > 2 ? 'are' : 'is'} ignored. Only cards show a list of icons.`,\n ]\n}\n"],"names":["ICON_ENTRY_OPTIONS","parseIconEntries","value","entries","warnings","raw","split","ref","options","trim","filter","Boolean","entry","option","separator","indexOf","key","slice","optionValue","replace","includes","push","join","palette","SINGLE_ICON_DIRECTIVES","Set","getExtraIconWarnings","directive","has","length","map"],"mappings":"AAAA;;;;;;;;;CASC,GAcD,MAAMA,qBAAqB;IAAC;CAAU;AAEtC,OAAO,SAASC,iBAAiBC,KAAyB;IACxD,MAAMC,UAAuB,EAAE;IAC/B,MAAMC,WAAqB,EAAE;IAE7B,KAAK,MAAMC,OAAOH,OAAOI,MAAM,QAAQ,EAAE,CAAE;QACzC,MAAM,CAACC,KAAK,GAAGC,QAAQ,GAAGH,IAAII,IAAI,GAAGH,KAAK,CAAC,OAAOI,MAAM,CAACC;QACzD,IAAI,CAACJ,KAAK;QAEV,MAAMK,QAAmB;YAAEL;QAAI;QAE/B,KAAK,MAAMM,UAAUL,QAAS;YAC5B,MAAMM,YAAYD,OAAOE,OAAO,CAAC;YACjC,MAAMC,MAAMF,YAAY,IAAID,OAAOI,KAAK,CAAC,GAAGH,aAAa;YACzD,MAAMI,cAAcJ,YAAY,IAAID,OAAOI,KAAK,CAACH,YAAY,GAAGK,OAAO,CAAC,gBAAgB,MAAM;YAE9F,IAAI,CAAC,AAACnB,mBAAyCoB,QAAQ,CAACJ,QAAQ,CAACE,aAAa;gBAC5Ed,SAASiB,IAAI,CACX,CAAC,qBAAqB,EAAER,OAAO,MAAM,EAAEN,IAAI,0CAA0C,EAAEP,mBAAmBsB,IAAI,CAAC,MAAM,CAAC,CAAC;gBAEzH;YACF;YAEAV,MAAMW,OAAO,GAAGL;QAClB;QAEAf,QAAQkB,IAAI,CAACT;IACf;IAEA,OAAO;QAAET;QAASC;IAAS;AAC7B;AAEA,sFAAsF,GACtF,MAAMoB,yBAAyB,IAAIC,IAAI;IAAC;IAAU;CAAU;AAE5D,OAAO,SAASC,qBAAqBC,SAAiB,EAAExB,OAAoB;IAC1E,IAAI,CAACqB,uBAAuBI,GAAG,CAACD,cAAcxB,QAAQ0B,MAAM,GAAG,GAAG,OAAO,EAAE;IAE3E,OAAO;QACL,CAAC,CAAC,EAAEF,UAAU,kBAAkB,EAAExB,QAC/Bc,KAAK,CAAC,GACNa,GAAG,CAAC,CAAClB,QAAU,CAAC,CAAC,EAAEA,MAAML,GAAG,CAAC,CAAC,CAAC,EAC/Be,IAAI,CAAC,MAAM,CAAC,EAAEnB,QAAQ0B,MAAM,GAAG,IAAI,QAAQ,KAAK,0CAA0C,CAAC;KAC/F;AACH"}
@@ -1,9 +1,10 @@
1
1
  import type { RootContent } from 'hast';
2
2
  import type { PayloadMarkdownIconsConfig } from '../types/core.js';
3
+ import { type SvgPaint } from './sanitizeSvg.js';
3
4
  export type PayloadMarkdownIconResolution = {
4
5
  iconKey?: string;
5
6
  nodes: RootContent[];
6
7
  warnings: string[];
7
8
  };
8
9
  export declare function validatePayloadMarkdownIconsConfig(config: PayloadMarkdownIconsConfig | undefined): string[];
9
- export declare function resolvePayloadMarkdownIcon(ref: string | undefined, config: PayloadMarkdownIconsConfig | undefined, className: string): PayloadMarkdownIconResolution;
10
+ export declare function resolvePayloadMarkdownIcon(ref: string | undefined, config: PayloadMarkdownIconsConfig | undefined, className: string, paint?: SvgPaint): PayloadMarkdownIconResolution;
@@ -50,7 +50,7 @@ function statFile(file) {
50
50
  return undefined;
51
51
  }
52
52
  }
53
- export function resolvePayloadMarkdownIcon(ref, config, className) {
53
+ export function resolvePayloadMarkdownIcon(ref, config, className, paint) {
54
54
  if (!ref) return {
55
55
  nodes: [],
56
56
  warnings: []
@@ -103,7 +103,7 @@ export function resolvePayloadMarkdownIcon(ref, config, className) {
103
103
  return {
104
104
  iconKey: normalized.icon.key,
105
105
  nodes: [
106
- instantiateSanitizedSvg(svg, className)
106
+ instantiateSanitizedSvg(svg, className, paint)
107
107
  ],
108
108
  warnings: []
109
109
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/icons/resolve.ts"],"sourcesContent":["import type { Element, RootContent } from 'hast'\n\nimport fs from 'node:fs'\nimport path from 'node:path'\n\nimport type { PayloadMarkdownIconsConfig } from '../types/core.js'\n\nimport {\n hasUnsafeIconPathSegments,\n normalizePayloadMarkdownIconRef,\n} from './refs.js'\nimport { instantiateSanitizedSvg, parseAndSanitizeSvg } from './sanitizeSvg.js'\n\nexport type PayloadMarkdownIconResolution = {\n iconKey?: string\n nodes: RootContent[]\n warnings: string[]\n}\n\nfunction isWithin(parent: string, child: string): boolean {\n const relative = path.relative(parent, child)\n\n return Boolean(relative) && !relative.startsWith('..') && !path.isAbsolute(relative)\n}\n\nexport function validatePayloadMarkdownIconsConfig(\n config: PayloadMarkdownIconsConfig | undefined,\n): string[] {\n if (!config) return []\n\n const warnings: string[] = []\n const seenAliases = new Set<string>()\n\n if (!config.baseDir?.trim()) warnings.push('Icon config baseDir must not be empty.')\n\n for (const pack of config.packs ?? []) {\n const alias = pack.alias.trim()\n const packPath = pack.path.trim()\n\n if (!alias) {\n warnings.push('Icon pack aliases must not be empty.')\n continue\n }\n\n if (seenAliases.has(alias)) warnings.push(`Duplicate icon pack alias \"${alias}\".`)\n seenAliases.add(alias)\n\n if (!packPath) warnings.push(`Icon pack \"${alias}\" path must not be empty.`)\n else if (hasUnsafeIconPathSegments(packPath))\n warnings.push(`Icon pack \"${alias}\" path must be a safe relative path.`)\n }\n\n return warnings\n}\n\ntype CachedIcon = {\n mtimeMs: number\n size: number\n svg: Element | undefined\n}\n\nconst MAX_CACHED_ICONS = 2000\nconst iconCache = new Map<string, CachedIcon>()\n\nfunction loadSanitizedIcon(iconFile: string, stats: fs.Stats): Element | undefined {\n const cached = iconCache.get(iconFile)\n\n if (cached && cached.mtimeMs === stats.mtimeMs && cached.size === stats.size) return cached.svg\n\n const svg = parseAndSanitizeSvg(fs.readFileSync(iconFile, 'utf8'))\n\n if (iconCache.size >= MAX_CACHED_ICONS) {\n const oldest = iconCache.keys().next().value\n if (oldest !== undefined) iconCache.delete(oldest)\n }\n\n iconCache.set(iconFile, { mtimeMs: stats.mtimeMs, size: stats.size, svg })\n\n return svg\n}\n\nfunction statFile(file: string): fs.Stats | undefined {\n try {\n const stats = fs.statSync(file)\n\n return stats.isFile() ? stats : undefined\n } catch {\n return undefined\n }\n}\n\nexport function resolvePayloadMarkdownIcon(\n ref: string | undefined,\n config: PayloadMarkdownIconsConfig | undefined,\n className: string,\n): PayloadMarkdownIconResolution {\n if (!ref) return { nodes: [], warnings: [] }\n\n const normalized = normalizePayloadMarkdownIconRef(ref)\n if (normalized.warning) return { nodes: [], warnings: [normalized.warning] }\n if (!normalized.icon) return { nodes: [], warnings: [] }\n\n const pack = config?.packs?.find((entry) => entry.alias === normalized.icon?.packAlias)\n if (!pack)\n return {\n iconKey: normalized.icon.key,\n nodes: [],\n warnings: [`Unknown icon pack \"${normalized.icon.packAlias}\".`],\n }\n\n const baseDir = path.resolve(process.cwd(), config?.baseDir ?? '')\n const packRoot = path.resolve(baseDir, pack.path)\n const iconFile = path.resolve(packRoot, `${normalized.icon.iconPath}.svg`)\n\n if (!isWithin(packRoot, iconFile))\n return {\n iconKey: normalized.icon.key,\n nodes: [],\n warnings: [`Malformed icon ref \"${ref}\". Icon paths must stay within their icon pack.`],\n }\n\n const stats = statFile(iconFile)\n\n if (!stats)\n return {\n iconKey: normalized.icon.key,\n nodes: [],\n warnings: [`Unknown icon \"${normalized.icon.key}\".`],\n }\n\n const svg = loadSanitizedIcon(iconFile, stats)\n\n if (!svg)\n return {\n iconKey: normalized.icon.key,\n nodes: [],\n warnings: [`Icon \"${normalized.icon.key}\" does not contain an <svg> element.`],\n }\n\n return {\n iconKey: normalized.icon.key,\n nodes: [instantiateSanitizedSvg(svg, className)],\n warnings: [],\n }\n}\n"],"names":["fs","path","hasUnsafeIconPathSegments","normalizePayloadMarkdownIconRef","instantiateSanitizedSvg","parseAndSanitizeSvg","isWithin","parent","child","relative","Boolean","startsWith","isAbsolute","validatePayloadMarkdownIconsConfig","config","warnings","seenAliases","Set","baseDir","trim","push","pack","packs","alias","packPath","has","add","MAX_CACHED_ICONS","iconCache","Map","loadSanitizedIcon","iconFile","stats","cached","get","mtimeMs","size","svg","readFileSync","oldest","keys","next","value","undefined","delete","set","statFile","file","statSync","isFile","resolvePayloadMarkdownIcon","ref","className","nodes","normalized","warning","icon","find","entry","packAlias","iconKey","key","resolve","process","cwd","packRoot","iconPath"],"mappings":"AAEA,OAAOA,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAI5B,SACEC,yBAAyB,EACzBC,+BAA+B,QAC1B,YAAW;AAClB,SAASC,uBAAuB,EAAEC,mBAAmB,QAAQ,mBAAkB;AAQ/E,SAASC,SAASC,MAAc,EAAEC,KAAa;IAC7C,MAAMC,WAAWR,KAAKQ,QAAQ,CAACF,QAAQC;IAEvC,OAAOE,QAAQD,aAAa,CAACA,SAASE,UAAU,CAAC,SAAS,CAACV,KAAKW,UAAU,CAACH;AAC7E;AAEA,OAAO,SAASI,mCACdC,MAA8C;IAE9C,IAAI,CAACA,QAAQ,OAAO,EAAE;IAEt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AAEoC,IAAI,+CAA+C,CAAC;SAAC;IACzF;IAEF,MAAMnB,QAAQc,SAASf;IAEvB,IAAI,CAACC,OACH,OAAO;QACL4B,SAASN,WAAWE,IAAI,CAACK,GAAG;QAC5BR,OAAO,EAAE;QACTtC,UAAU;YAAC,CAAC,cAAc,EAAEuC,WAAWE,IAAI,CAACK,GAAG,CAAC,EAAE,CAAC;SAAC;IACtD;IAEF,MAAMxB,MAAMP,kBAAkBC,UAAUC;IAExC,IAAI,CAACK,KACH,OAAO;QACLuB,SAASN,WAAWE,IAAI,CAACK,GAAG;QAC5BR,OAAO,EAAE;QACTtC,UAAU;YAAC,CAAC,MAAM,EAAEuC,WAAWE,IAAI,CAACK,GAAG,CAAC,oCAAoC,CAAC;SAAC;IAChF;IAEF,OAAO;QACLD,SAASN,WAAWE,IAAI,CAACK,GAAG;QAC5BR,OAAO;YAACjD,wBAAwBiC,KAAKe;SAAW;QAChDrC,UAAU,EAAE;IACd;AACF"}
1
+ {"version":3,"sources":["../../src/icons/resolve.ts"],"sourcesContent":["import type { Element, RootContent } from 'hast'\n\nimport fs from 'node:fs'\nimport path from 'node:path'\n\nimport type { PayloadMarkdownIconsConfig } from '../types/core.js'\n\nimport {\n hasUnsafeIconPathSegments,\n normalizePayloadMarkdownIconRef,\n} from './refs.js'\nimport { instantiateSanitizedSvg, parseAndSanitizeSvg, type SvgPaint } from './sanitizeSvg.js'\n\nexport type PayloadMarkdownIconResolution = {\n iconKey?: string\n nodes: RootContent[]\n warnings: string[]\n}\n\nfunction isWithin(parent: string, child: string): boolean {\n const relative = path.relative(parent, child)\n\n return Boolean(relative) && !relative.startsWith('..') && !path.isAbsolute(relative)\n}\n\nexport function validatePayloadMarkdownIconsConfig(\n config: PayloadMarkdownIconsConfig | undefined,\n): string[] {\n if (!config) return []\n\n const warnings: string[] = []\n const seenAliases = new Set<string>()\n\n if (!config.baseDir?.trim()) warnings.push('Icon config baseDir must not be empty.')\n\n for (const pack of config.packs ?? []) {\n const alias = pack.alias.trim()\n const packPath = pack.path.trim()\n\n if (!alias) {\n warnings.push('Icon pack aliases must not be empty.')\n continue\n }\n\n if (seenAliases.has(alias)) warnings.push(`Duplicate icon pack alias \"${alias}\".`)\n seenAliases.add(alias)\n\n if (!packPath) warnings.push(`Icon pack \"${alias}\" path must not be empty.`)\n else if (hasUnsafeIconPathSegments(packPath))\n warnings.push(`Icon pack \"${alias}\" path must be a safe relative path.`)\n }\n\n return warnings\n}\n\ntype CachedIcon = {\n mtimeMs: number\n size: number\n svg: Element | undefined\n}\n\nconst MAX_CACHED_ICONS = 2000\nconst iconCache = new Map<string, CachedIcon>()\n\nfunction loadSanitizedIcon(iconFile: string, stats: fs.Stats): Element | undefined {\n const cached = iconCache.get(iconFile)\n\n if (cached && cached.mtimeMs === stats.mtimeMs && cached.size === stats.size) return cached.svg\n\n const svg = parseAndSanitizeSvg(fs.readFileSync(iconFile, 'utf8'))\n\n if (iconCache.size >= MAX_CACHED_ICONS) {\n const oldest = iconCache.keys().next().value\n if (oldest !== undefined) iconCache.delete(oldest)\n }\n\n iconCache.set(iconFile, { mtimeMs: stats.mtimeMs, size: stats.size, svg })\n\n return svg\n}\n\nfunction statFile(file: string): fs.Stats | undefined {\n try {\n const stats = fs.statSync(file)\n\n return stats.isFile() ? stats : undefined\n } catch {\n return undefined\n }\n}\n\nexport function resolvePayloadMarkdownIcon(\n ref: string | undefined,\n config: PayloadMarkdownIconsConfig | undefined,\n className: string,\n paint?: SvgPaint,\n): PayloadMarkdownIconResolution {\n if (!ref) return { nodes: [], warnings: [] }\n\n const normalized = normalizePayloadMarkdownIconRef(ref)\n if (normalized.warning) return { nodes: [], warnings: [normalized.warning] }\n if (!normalized.icon) return { nodes: [], warnings: [] }\n\n const pack = config?.packs?.find((entry) => entry.alias === normalized.icon?.packAlias)\n if (!pack)\n return {\n iconKey: normalized.icon.key,\n nodes: [],\n warnings: [`Unknown icon pack \"${normalized.icon.packAlias}\".`],\n }\n\n const baseDir = path.resolve(process.cwd(), config?.baseDir ?? '')\n const packRoot = path.resolve(baseDir, pack.path)\n const iconFile = path.resolve(packRoot, `${normalized.icon.iconPath}.svg`)\n\n if (!isWithin(packRoot, iconFile))\n return {\n iconKey: normalized.icon.key,\n nodes: [],\n warnings: [`Malformed icon ref \"${ref}\". Icon paths must stay within their icon pack.`],\n }\n\n const stats = statFile(iconFile)\n\n if (!stats)\n return {\n iconKey: normalized.icon.key,\n nodes: [],\n warnings: [`Unknown icon \"${normalized.icon.key}\".`],\n }\n\n const svg = loadSanitizedIcon(iconFile, stats)\n\n if (!svg)\n return {\n iconKey: normalized.icon.key,\n nodes: [],\n warnings: [`Icon \"${normalized.icon.key}\" does not contain an <svg> element.`],\n }\n\n return {\n iconKey: normalized.icon.key,\n nodes: [instantiateSanitizedSvg(svg, className, paint)],\n warnings: [],\n }\n}\n"],"names":["fs","path","hasUnsafeIconPathSegments","normalizePayloadMarkdownIconRef","instantiateSanitizedSvg","parseAndSanitizeSvg","isWithin","parent","child","relative","Boolean","startsWith","isAbsolute","validatePayloadMarkdownIconsConfig","config","warnings","seenAliases","Set","baseDir","trim","push","pack","packs","alias","packPath","has","add","MAX_CACHED_ICONS","iconCache","Map","loadSanitizedIcon","iconFile","stats","cached","get","mtimeMs","size","svg","readFileSync","oldest","keys","next","value","undefined","delete","set","statFile","file","statSync","isFile","resolvePayloadMarkdownIcon","ref","className","paint","nodes","normalized","warning","icon","find","entry","packAlias","iconKey","key","resolve","process","cwd","packRoot","iconPath"],"mappings":"AAEA,OAAOA,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAI5B,SACEC,yBAAyB,EACzBC,+BAA+B,QAC1B,YAAW;AAClB,SAASC,uBAAuB,EAAEC,mBAAmB,QAAuB,mBAAkB;AAQ9F,SAASC,SAASC,MAAc,EAAEC,KAAa;IAC7C,MAAMC,WAAWR,KAAKQ,QAAQ,CAACF,QAAQC;IAEvC,OAAOE,QAAQD,aAAa,CAACA,SAASE,UAAU,CAAC,SAAS,CAAC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D,UAAUnC,WACtB,OAAO;QACL8B,SAASN,WAAWE,IAAI,CAACK,GAAG;QAC5BR,OAAO,EAAE;QACTvC,UAAU;YAAC,CAAC,oBAAoB,EAAEoC,IAAI,+CAA+C,CAAC;SAAC;IACzF;IAEF,MAAMnB,QAAQc,SAASf;IAEvB,IAAI,CAACC,OACH,OAAO;QACL6B,SAASN,WAAWE,IAAI,CAACK,GAAG;QAC5BR,OAAO,EAAE;QACTvC,UAAU;YAAC,CAAC,cAAc,EAAEwC,WAAWE,IAAI,CAACK,GAAG,CAAC,EAAE,CAAC;SAAC;IACtD;IAEF,MAAMzB,MAAMP,kBAAkBC,UAAUC;IAExC,IAAI,CAACK,KACH,OAAO;QACLwB,SAASN,WAAWE,IAAI,CAACK,GAAG;QAC5BR,OAAO,EAAE;QACTvC,UAAU;YAAC,CAAC,MAAM,EAAEwC,WAAWE,IAAI,CAACK,GAAG,CAAC,oCAAoC,CAAC;SAAC;IAChF;IAEF,OAAO;QACLD,SAASN,WAAWE,IAAI,CAACK,GAAG;QAC5BR,OAAO;YAAClD,wBAAwBiC,KAAKe,WAAWC;SAAO;QACvDtC,UAAU,EAAE;IACd;AACF"}
@@ -4,8 +4,18 @@ import type { Element } from 'hast';
4
4
  * element, or `undefined` when the file has none.
5
5
  */
6
6
  export declare function parseAndSanitizeSvg(content: string): Element | undefined;
7
+ /** How a palette paints an icon (all values are validated CSS colours). */
8
+ export type SvgPaint = {
9
+ /** Palette name, emitted as `data-pmd-palette`. */
10
+ name: string;
11
+ primary?: string;
12
+ secondary?: string;
13
+ secondaryOpacity?: number;
14
+ };
7
15
  /**
8
16
  * Returns a deep copy of a sanitized icon with the runtime class names and
9
- * accessibility attributes the renderer adds to every inline icon.
17
+ * accessibility attributes the renderer adds to every inline icon. With a
18
+ * `paint`, the copy is recoloured with its palette (see `applyPaint`); without
19
+ * one it is left exactly as the icon file draws it.
10
20
  */
11
- export declare function instantiateSanitizedSvg(svg: Element, className: string): Element;
21
+ export declare function instantiateSanitizedSvg(svg: Element, className: string, paint?: SvgPaint): Element;
@@ -401,13 +401,99 @@ function toClassList(value) {
401
401
  if (typeof value === 'string') return value.split(/\s+/).filter(Boolean);
402
402
  return [];
403
403
  }
404
+ /** Classes that mark a duotone icon's secondary layer (Font Awesome and our own). */ const SECONDARY_LAYER_CLASSES = [
405
+ 'fa-secondary',
406
+ 'pmd-icon-secondary'
407
+ ];
408
+ /** Paint values a palette may replace: real colours, not `none`, `currentColor` or `url(#…)` refs. */ function isRecolorablePaint(value) {
409
+ if (typeof value !== 'string') return false;
410
+ const paint = value.trim().toLowerCase();
411
+ return Boolean(paint) && ![
412
+ 'currentcolor',
413
+ 'inherit',
414
+ 'none',
415
+ 'transparent'
416
+ ].includes(paint) && !paint.startsWith('url(');
417
+ }
418
+ function recolorStyle(value, replacement) {
419
+ if (typeof value !== 'string') return undefined;
420
+ const declarations = value.split(';').map((declaration)=>declaration.trim()).filter(Boolean).flatMap((declaration)=>{
421
+ const separator = declaration.indexOf(':');
422
+ const property = declaration.slice(0, separator).trim().toLowerCase();
423
+ if ((property === 'fill' || property === 'stroke') && isRecolorablePaint(declaration.slice(separator + 1))) return replacement ? [
424
+ `${property}:${replacement}`
425
+ ] : [];
426
+ return [
427
+ declaration
428
+ ];
429
+ });
430
+ return declarations.length > 0 ? declarations.join(';') : undefined;
431
+ }
432
+ /**
433
+ * Recolours a palette-painted icon in place. Explicit fill/stroke colours
434
+ * become `currentColor` (the palette colour); the duotone secondary layer is
435
+ * painted with `--pmd-icon-secondary` and its own subtree inherits from it.
436
+ */ /**
437
+ * Elements whose colours define coverage or a paint server rather than what
438
+ * the icon looks like (a white mask rect means "fully visible"). Painting
439
+ * never touches their subtrees.
440
+ */ const UNPAINTED_TAG_NAMES = new Set([
441
+ 'clipPath',
442
+ 'filter',
443
+ 'linearGradient',
444
+ 'mask',
445
+ 'pattern',
446
+ 'radialGradient'
447
+ ]);
448
+ const SECONDARY_PAINT = 'var(--pmd-icon-secondary, currentColor)';
449
+ /**
450
+ * Recolours a palette-painted icon in place. Explicit fill/stroke colours
451
+ * become `currentColor` (the palette colour); inside the duotone secondary
452
+ * layer they become the secondary colour, and the layer itself is filled
453
+ * with it unless it draws with `fill="none"`.
454
+ */ function applyPaint(node, paint, inSecondary) {
455
+ if (UNPAINTED_TAG_NAMES.has(node.tagName)) return;
456
+ const layerRoot = !inSecondary && toClassList(node.properties.className).some((name)=>SECONDARY_LAYER_CLASSES.includes(name));
457
+ const secondary = inSecondary || layerRoot;
458
+ const replacement = secondary ? SECONDARY_PAINT : 'currentColor';
459
+ // Attributes cannot hold var(), so secondary colours go into the style.
460
+ const declarations = [];
461
+ for (const property of [
462
+ 'fill',
463
+ 'stroke'
464
+ ])if (isRecolorablePaint(node.properties[property])) {
465
+ if (secondary) {
466
+ delete node.properties[property];
467
+ declarations.push(`${property}:${SECONDARY_PAINT}`);
468
+ } else {
469
+ node.properties[property] = 'currentColor';
470
+ }
471
+ }
472
+ const style = recolorStyle(node.properties.style, replacement);
473
+ if (layerRoot && node.properties.fill !== 'none' && !declarations.some((declaration)=>declaration.startsWith('fill:')) && !/(?:^|;)\s*fill\s*:/.test(style ?? '')) declarations.push(`fill:${SECONDARY_PAINT}`);
474
+ if (layerRoot && paint.secondaryOpacity !== undefined) node.properties.opacity = String(paint.secondaryOpacity);
475
+ const combined = [
476
+ style,
477
+ ...declarations
478
+ ].filter(Boolean).join(';');
479
+ if (combined) node.properties.style = combined;
480
+ else delete node.properties.style;
481
+ for (const child of node.children)if (child.type === 'element') applyPaint(child, paint, secondary);
482
+ }
404
483
  /**
405
484
  * Returns a deep copy of a sanitized icon with the runtime class names and
406
- * accessibility attributes the renderer adds to every inline icon.
407
- */ export function instantiateSanitizedSvg(svg, className) {
485
+ * accessibility attributes the renderer adds to every inline icon. With a
486
+ * `paint`, the copy is recoloured with its palette (see `applyPaint`); without
487
+ * one it is left exactly as the icon file draws it.
488
+ */ export function instantiateSanitizedSvg(svg, className, paint) {
408
489
  const copy = structuredClone(svg);
409
490
  const properties = {};
410
- const runtimeClasses = className.split(/\s+/).filter(Boolean);
491
+ const runtimeClasses = [
492
+ ...className.split(/\s+/).filter(Boolean),
493
+ ...paint ? [
494
+ 'pmd-icon--palette'
495
+ ] : []
496
+ ];
411
497
  let hasClass = false;
412
498
  for (const [name, value] of Object.entries(copy.properties)){
413
499
  if (name === 'ariaHidden' || name === 'focusable') continue;
@@ -425,6 +511,21 @@ function toClassList(value) {
425
511
  properties.ariaHidden = 'true';
426
512
  properties.focusable = 'false';
427
513
  copy.properties = properties;
514
+ if (paint) {
515
+ for (const child of copy.children)if (child.type === 'element') applyPaint(child, paint, false);
516
+ // Icons that set no fill (Font Awesome brands, for one) would paint black.
517
+ if (properties.fill === undefined) properties.fill = 'currentColor';
518
+ else if (isRecolorablePaint(properties.fill)) properties.fill = 'currentColor';
519
+ if (isRecolorablePaint(properties.stroke)) properties.stroke = 'currentColor';
520
+ const declarations = [
521
+ recolorStyle(properties.style, 'currentColor'),
522
+ paint.primary ? `color:${paint.primary}` : undefined,
523
+ paint.secondary ? `--pmd-icon-secondary:${paint.secondary}` : undefined
524
+ ].filter(Boolean);
525
+ if (declarations.length > 0) properties.style = declarations.join(';');
526
+ else delete properties.style;
527
+ properties.dataPmdPalette = paint.name;
528
+ }
428
529
  return copy;
429
530
  }
430
531
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/icons/sanitizeSvg.ts"],"sourcesContent":["import type { Element, ElementContent, Properties, Root, RootContent } from 'hast'\n\nimport { fromHtml } from 'hast-util-from-html'\n\n/**\n * Structured sanitizer for icon SVG files (CORE-4).\n *\n * Icons are inlined into rendered markdown after rehype-sanitize has run, so\n * this is the only line of defence for icon file content. The file is parsed\n * with a real HTML parser (foreign-content SVG rules), only the first top-level\n * `<svg>` is kept, and its subtree is filtered through a strict allowlist:\n *\n * - elements outside the allowlist are dropped with their content\n * (`script`, `style`, `foreignObject`, `animate*`, `set`, `image`, `iframe`, …);\n * `<a>` is unwrapped so its drawing content survives without the link\n * - attributes outside the allowlist are dropped, which includes every `on*`\n * handler and `data-*` attribute\n * - `href` / `xlink:href` are kept only as same-document `#fragment` refs\n * - `style` attributes are kept only when they cannot load or reference\n * anything (`url(`, `@import`, `expression(`, `javascript:`, escapes)\n * - `<style>` elements are never emitted (inlined into the page they would apply\n * to the whole document). Simple class rules that only set paint/opacity —\n * e.g. Font Awesome duotone's `.fa-secondary{opacity:.4}` — are translated into\n * presentation attributes on the matching elements of the same icon, so icons\n * keep their appearance without carrying CSS. Any rule that is not a plain\n * class selector with allowlisted properties and plain values is ignored.\n */\n\nconst ALLOWED_SVG_TAG_NAMES = new Set([\n 'circle',\n 'clipPath',\n 'defs',\n 'desc',\n 'ellipse',\n 'feBlend',\n 'feColorMatrix',\n 'feComponentTransfer',\n 'feComposite',\n 'feConvolveMatrix',\n 'feDiffuseLighting',\n 'feDisplacementMap',\n 'feDistantLight',\n 'feDropShadow',\n 'feFlood',\n 'feFuncA',\n 'feFuncB',\n 'feFuncG',\n 'feFuncR',\n 'feGaussianBlur',\n 'feMerge',\n 'feMergeNode',\n 'feMorphology',\n 'feOffset',\n 'fePointLight',\n 'feSpecularLighting',\n 'feSpotLight',\n 'feTile',\n 'feTurbulence',\n 'filter',\n 'g',\n 'line',\n 'linearGradient',\n 'marker',\n 'mask',\n 'path',\n 'pattern',\n 'polygon',\n 'polyline',\n 'radialGradient',\n 'rect',\n 'stop',\n 'svg',\n 'symbol',\n 'text',\n 'textPath',\n 'title',\n 'tspan',\n 'use',\n])\n\n/** Elements whose children are kept while the element itself is removed. */\nconst UNWRAP_SVG_TAG_NAMES = new Set(['a'])\n\n/** Allowed attributes, written as they appear in SVG source. */\nconst ALLOWED_SVG_ATTRIBUTES = [\n 'alignment-baseline',\n 'amplitude',\n 'aria-hidden',\n 'aria-label',\n 'azimuth',\n 'baseFrequency',\n 'baseline-shift',\n 'bias',\n 'class',\n 'clip-path',\n 'clip-rule',\n 'clipPathUnits',\n 'color',\n 'color-interpolation-filters',\n 'cx',\n 'cy',\n 'd',\n 'diffuseConstant',\n 'display',\n 'divisor',\n 'dominant-baseline',\n 'dx',\n 'dy',\n 'edgeMode',\n 'elevation',\n 'exponent',\n 'fill',\n 'fill-opacity',\n 'fill-rule',\n 'filter',\n 'filterUnits',\n 'flood-color',\n 'flood-opacity',\n 'focusable',\n 'font-family',\n 'font-size',\n 'font-style',\n 'font-weight',\n 'fr',\n 'fx',\n 'fy',\n 'gradientTransform',\n 'gradientUnits',\n 'height',\n 'id',\n 'in',\n 'in2',\n 'intercept',\n 'k1',\n 'k2',\n 'k3',\n 'k4',\n 'kernelMatrix',\n 'lengthAdjust',\n 'letter-spacing',\n 'lighting-color',\n 'limitingConeAngle',\n 'marker-end',\n 'marker-mid',\n 'marker-start',\n 'markerHeight',\n 'markerUnits',\n 'markerWidth',\n 'mask',\n 'maskContentUnits',\n 'maskUnits',\n 'mode',\n 'numOctaves',\n 'offset',\n 'opacity',\n 'operator',\n 'order',\n 'orient',\n 'overflow',\n 'paint-order',\n 'pathLength',\n 'patternContentUnits',\n 'patternTransform',\n 'patternUnits',\n 'points',\n 'pointsAtX',\n 'pointsAtY',\n 'pointsAtZ',\n 'preserveAlpha',\n 'preserveAspectRatio',\n 'primitiveUnits',\n 'r',\n 'radius',\n 'refX',\n 'refY',\n 'result',\n 'role',\n 'rx',\n 'ry',\n 'scale',\n 'seed',\n 'shape-rendering',\n 'slope',\n 'specularConstant',\n 'specularExponent',\n 'spreadMethod',\n 'startOffset',\n 'stdDeviation',\n 'stitchTiles',\n 'stop-color',\n 'stop-opacity',\n 'stroke',\n 'stroke-dasharray',\n 'stroke-dashoffset',\n 'stroke-linecap',\n 'stroke-linejoin',\n 'stroke-miterlimit',\n 'stroke-opacity',\n 'stroke-width',\n 'style',\n 'surfaceScale',\n 'tableValues',\n 'targetX',\n 'targetY',\n 'text-anchor',\n 'text-decoration',\n 'textLength',\n 'transform',\n 'type',\n 'values',\n 'vector-effect',\n 'version',\n 'viewBox',\n 'visibility',\n 'width',\n 'word-spacing',\n 'x',\n 'x1',\n 'x2',\n 'xChannelSelector',\n 'xmlns',\n 'xmlns:xlink',\n 'y',\n 'y1',\n 'y2',\n 'yChannelSelector',\n 'z',\n]\n\nconst FRAGMENT_ONLY_ATTRIBUTES = ['href', 'xlink:href']\n\nfunction getSvgPropertyNames(attributes: readonly string[]): Set<string> {\n // Let the same parser that reads icon files tell us the hast property name\n // for each attribute, so the allowlist cannot drift from parsing.\n const markup = `<svg ${attributes.map((attribute) => `${attribute}=\"\"`).join(' ')}></svg>`\n const svg = fromHtml(markup, { fragment: true }).children[0] as Element | undefined\n\n return new Set(Object.keys(svg?.properties ?? {}))\n}\n\nconst ALLOWED_SVG_PROPERTIES = getSvgPropertyNames(ALLOWED_SVG_ATTRIBUTES)\nconst FRAGMENT_ONLY_PROPERTIES = getSvgPropertyNames(FRAGMENT_ONLY_ATTRIBUTES)\n\nconst UNSAFE_STYLE_PATTERN = /url\\s*\\(|@import|expression\\s*\\(|javascript:|\\\\|<|behavior\\s*:|-moz-binding/i\n\nfunction isSafeStyle(value: Properties[string]): boolean {\n return typeof value === 'string' && !UNSAFE_STYLE_PATTERN.test(value)\n}\n\nfunction sanitizeProperties(properties: Properties | undefined): Properties {\n const output: Properties = {}\n\n for (const [name, value] of Object.entries(properties ?? {})) {\n if (FRAGMENT_ONLY_PROPERTIES.has(name)) {\n if (typeof value === 'string' && value.trim().startsWith('#')) output[name] = value.trim()\n continue\n }\n\n if (!ALLOWED_SVG_PROPERTIES.has(name)) continue\n if (name === 'style' && !isSafeStyle(value)) continue\n\n output[name] = value\n }\n\n return output\n}\n\n/**\n * Presentation properties a `<style>` class rule may set (they are also allowed as SVG attributes).\n * Design-tool exports (Illustrator, Figma, Sketch) put their paint in such rules, for example\n * `.cls-1{fill:#0a84ff;stroke-miterlimit:10}`.\n */\nconst STYLE_RULE_PROPERTIES = [\n 'clip-rule',\n 'color',\n 'display',\n 'fill',\n 'fill-opacity',\n 'fill-rule',\n 'flood-color',\n 'flood-opacity',\n 'font-family',\n 'font-size',\n 'font-style',\n 'font-weight',\n 'letter-spacing',\n 'lighting-color',\n 'opacity',\n 'paint-order',\n 'shape-rendering',\n 'stop-color',\n 'stop-opacity',\n 'stroke',\n 'stroke-dasharray',\n 'stroke-dashoffset',\n 'stroke-linecap',\n 'stroke-linejoin',\n 'stroke-miterlimit',\n 'stroke-opacity',\n 'stroke-width',\n 'text-anchor',\n 'vector-effect',\n 'visibility',\n]\nconst STYLE_RULE_PROPERTY_NAMES = new Map(\n STYLE_RULE_PROPERTIES.map((attribute) => [attribute, [...getSvgPropertyNames([attribute])][0]]),\n)\n/**\n * A plain value: numbers and lengths (also space/comma-separated lists such as dash arrays), hex\n * colours, keywords, quoted font names, and rgb()/rgba()/hsl()/hsla() with numeric arguments.\n * Anything that can load or reference something (`url(`, other functions, escapes) is rejected.\n */\nconst SAFE_STYLE_VALUE =\n /^(?:#[0-9a-f]{3,8}|(?:rgba?|hsla?)\\([\\d\\s.,%/-]+\\)|[\\w\\s.,%\"'-]+)$/i\nconst CLASS_SELECTOR = /^\\.(-?[_a-z][\\w-]*)$/i\n\ntype StyleRule = { className: string; declarations: Array<[string, string]> }\n\nfunction collectText(node: Element): string {\n return node.children.map((child) => (child.type === 'text' ? child.value : child.type === 'element' ? collectText(child) : '')).join('')\n}\n\nfunction collectStyleText(children: readonly (ElementContent | RootContent)[]): string {\n let text = ''\n\n for (const child of children) {\n if (child.type !== 'element') continue\n if (child.tagName === 'style') text += `${collectText(child)}\\n`\n else text += collectStyleText(child.children)\n }\n\n return text\n}\n\n/** Parses only `.class[, .class] { prop: value; … }` rules with allowlisted properties and plain values. */\nfunction parseClassStyleRules(css: string): StyleRule[] {\n const rules: StyleRule[] = []\n const withoutComments = css.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n\n for (const match of withoutComments.matchAll(/([^{}]+)\\{([^{}]*)\\}/g)) {\n const selectors = match[1].split(',').map((selector) => selector.trim())\n const classNames = selectors.map((selector) => CLASS_SELECTOR.exec(selector)?.[1])\n if (classNames.some((name) => !name)) continue\n\n const declarations: Array<[string, string]> = []\n\n // Each declaration stands alone, like CSS: unsupported properties (e.g. `isolation`) and\n // unsafe values are skipped without discarding the rule's other, safe declarations.\n for (const declaration of match[2].split(';')) {\n const separator = declaration.indexOf(':')\n if (separator < 0) continue\n const property = declaration.slice(0, separator).trim().toLowerCase()\n const value = declaration.slice(separator + 1).replace(/\\s*!important\\s*$/i, '').trim()\n const propertyName = STYLE_RULE_PROPERTY_NAMES.get(property)\n\n if (!propertyName || !value || !SAFE_STYLE_VALUE.test(value)) continue\n\n declarations.push([propertyName, value])\n }\n\n if (declarations.length === 0) continue\n for (const className of classNames) rules.push({ className: className!, declarations })\n }\n\n return rules\n}\n\nfunction applyClassStyleRules(node: Element, rules: readonly StyleRule[]): void {\n const classes = toClassList(node.properties.className)\n\n // Later rules win, like the stylesheet they replace; class rules outrank presentation attributes.\n for (const rule of rules) {\n if (!classes.includes(rule.className)) continue\n for (const [name, value] of rule.declarations) node.properties[name] = value\n }\n\n for (const child of node.children) if (child.type === 'element') applyClassStyleRules(child, rules)\n}\n\nfunction sanitizeChildren(children: readonly (ElementContent | RootContent)[]): ElementContent[] {\n const output: ElementContent[] = []\n\n for (const child of children) {\n if (child.type === 'text') {\n output.push({ type: 'text', value: child.value })\n continue\n }\n\n if (child.type !== 'element') continue\n\n if (UNWRAP_SVG_TAG_NAMES.has(child.tagName)) {\n output.push(...sanitizeChildren(child.children))\n continue\n }\n\n if (!ALLOWED_SVG_TAG_NAMES.has(child.tagName)) continue\n\n output.push({\n type: 'element',\n children: sanitizeChildren(child.children),\n properties: sanitizeProperties(child.properties),\n tagName: child.tagName,\n })\n }\n\n return output\n}\n\n/**\n * Parses SVG file content and returns the sanitized first top-level `<svg>`\n * element, or `undefined` when the file has none.\n */\nexport function parseAndSanitizeSvg(content: string): Element | undefined {\n const root: Root = fromHtml(content, { fragment: true })\n const svg = root.children.find(\n (node): node is Element => node.type === 'element' && node.tagName === 'svg',\n )\n\n if (!svg) return undefined\n\n const sanitized: Element = {\n type: 'element',\n children: sanitizeChildren(svg.children),\n properties: sanitizeProperties(svg.properties),\n tagName: 'svg',\n }\n const styleRules = parseClassStyleRules(collectStyleText(svg.children))\n\n if (styleRules.length > 0) applyClassStyleRules(sanitized, styleRules)\n\n return sanitized\n}\n\nfunction toClassList(value: Properties[string]): string[] {\n if (Array.isArray(value)) return value.map(String)\n if (typeof value === 'string') return value.split(/\\s+/).filter(Boolean)\n\n return []\n}\n\n/**\n * Returns a deep copy of a sanitized icon with the runtime class names and\n * accessibility attributes the renderer adds to every inline icon.\n */\nexport function instantiateSanitizedSvg(svg: Element, className: string): Element {\n const copy = structuredClone(svg)\n const properties: Properties = {}\n const runtimeClasses = className.split(/\\s+/).filter(Boolean)\n let hasClass = false\n\n for (const [name, value] of Object.entries(copy.properties)) {\n if (name === 'ariaHidden' || name === 'focusable') continue\n\n if (name === 'className') {\n hasClass = true\n properties.className = [...toClassList(value), ...runtimeClasses]\n continue\n }\n\n properties[name] = value\n }\n\n if (!hasClass) properties.className = runtimeClasses\n\n properties.ariaHidden = 'true'\n properties.focusable = 'false'\n copy.properties = properties\n\n return copy\n}\n"],"names":["fromHtml","ALLOWED_SVG_TAG_NAMES","Set","UNWRAP_SVG_TAG_NAMES","ALLOWED_SVG_ATTRIBUTES","FRAGMENT_ONLY_ATTRIBUTES","getSvgPropertyNames","attributes","markup","map","attribute","join","svg","fragment","children","Object","keys","properties","ALLOWED_SVG_PROPERTIES","FRAGMENT_ONLY_PROPERTIES","UNSAFE_STYLE_PATTERN","isSafeStyle","value","test","sanitizeProperties","output","name","entries","has","trim","startsWith","STYLE_RULE_PROPERTIES","STYLE_RULE_PROPERTY_NAMES","Map","SAFE_STYLE_VALUE","CLASS_SELECTOR","collectText","node","child","type","collectStyleText","text","tagName","parseClassStyleRules","css","rules","withoutComments","replace","match","matchAll","selectors","split","selector","classNames","exec","some","declarations","declaration","separator","indexOf","property","slice","toLowerCase","propertyName","get","push","length","className","applyClassStyleRules","classes","toClassList","rule","includes","sanitizeChildren","parseAndSanitizeSvg","content","root","find","undefined","sanitized","styleRules","Array","isArray","String","filter","Boolean","instantiateSanitizedSvg","copy","structuredClone","runtimeClasses","hasClass","ariaHidden","focusable"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,sBAAqB;AAE9C;;;;;;;;;;;;;;;;;;;;;;CAsBC,GAED,MAAMC,wBAAwB,IAAIC,IAAI;IACpC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,0EAA0E,GAC1E,MAAMC,uBAAuB,IAAID,IAAI;IAAC;CAAI;AAE1C,8DAA8D,GAC9D,MAAME,yBAAyB;IAC7B;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;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CAGC,GACD,OAAO,SAASC,wBAAwB1E,GAAY,EAAEuD,SAAiB;IACrE,MAAMoB,OAAOC,gBAAgB5E;IAC7B,MAAMK,aAAyB,CAAC;IAChC,MAAMwE,iBAAiBtB,UAAUhB,KAAK,CAAC,OAAOiC,MAAM,CAACC;IACrD,IAAIK,WAAW;IAEf,KAAK,MAAM,CAAChE,MAAMJ,MAAM,IAAIP,OAAOY,OAAO,CAAC4D,KAAKtE,UAAU,EAAG;QAC3D,IAAIS,SAAS,gBAAgBA,SAAS,aAAa;QAEnD,IAAIA,SAAS,aAAa;YACxBgE,WAAW;YACXzE,WAAWkD,SAAS,GAAG;mBAAIG,YAAYhD;mBAAWmE;aAAe;YACjE;QACF;QAEAxE,UAAU,CAACS,KAAK,GAAGJ;IACrB;IAEA,IAAI,CAACoE,UAAUzE,WAAWkD,SAAS,GAAGsB;IAEtCxE,WAAW0E,UAAU,GAAG;IACxB1E,WAAW2E,SAAS,GAAG;IACvBL,KAAKtE,UAAU,GAAGA;IAElB,OAAOsE;AACT"}
1
+ {"version":3,"sources":["../../src/icons/sanitizeSvg.ts"],"sourcesContent":["import type { Element, ElementContent, Properties, Root, RootContent } from 'hast'\n\nimport { fromHtml } from 'hast-util-from-html'\n\n/**\n * Structured sanitizer for icon SVG files (CORE-4).\n *\n * Icons are inlined into rendered markdown after rehype-sanitize has run, so\n * this is the only line of defence for icon file content. The file is parsed\n * with a real HTML parser (foreign-content SVG rules), only the first top-level\n * `<svg>` is kept, and its subtree is filtered through a strict allowlist:\n *\n * - elements outside the allowlist are dropped with their content\n * (`script`, `style`, `foreignObject`, `animate*`, `set`, `image`, `iframe`, …);\n * `<a>` is unwrapped so its drawing content survives without the link\n * - attributes outside the allowlist are dropped, which includes every `on*`\n * handler and `data-*` attribute\n * - `href` / `xlink:href` are kept only as same-document `#fragment` refs\n * - `style` attributes are kept only when they cannot load or reference\n * anything (`url(`, `@import`, `expression(`, `javascript:`, escapes)\n * - `<style>` elements are never emitted (inlined into the page they would apply\n * to the whole document). Simple class rules that only set paint/opacity —\n * e.g. Font Awesome duotone's `.fa-secondary{opacity:.4}` — are translated into\n * presentation attributes on the matching elements of the same icon, so icons\n * keep their appearance without carrying CSS. Any rule that is not a plain\n * class selector with allowlisted properties and plain values is ignored.\n */\n\nconst ALLOWED_SVG_TAG_NAMES = new Set([\n 'circle',\n 'clipPath',\n 'defs',\n 'desc',\n 'ellipse',\n 'feBlend',\n 'feColorMatrix',\n 'feComponentTransfer',\n 'feComposite',\n 'feConvolveMatrix',\n 'feDiffuseLighting',\n 'feDisplacementMap',\n 'feDistantLight',\n 'feDropShadow',\n 'feFlood',\n 'feFuncA',\n 'feFuncB',\n 'feFuncG',\n 'feFuncR',\n 'feGaussianBlur',\n 'feMerge',\n 'feMergeNode',\n 'feMorphology',\n 'feOffset',\n 'fePointLight',\n 'feSpecularLighting',\n 'feSpotLight',\n 'feTile',\n 'feTurbulence',\n 'filter',\n 'g',\n 'line',\n 'linearGradient',\n 'marker',\n 'mask',\n 'path',\n 'pattern',\n 'polygon',\n 'polyline',\n 'radialGradient',\n 'rect',\n 'stop',\n 'svg',\n 'symbol',\n 'text',\n 'textPath',\n 'title',\n 'tspan',\n 'use',\n])\n\n/** Elements whose children are kept while the element itself is removed. */\nconst UNWRAP_SVG_TAG_NAMES = new Set(['a'])\n\n/** Allowed attributes, written as they appear in SVG source. */\nconst ALLOWED_SVG_ATTRIBUTES = [\n 'alignment-baseline',\n 'amplitude',\n 'aria-hidden',\n 'aria-label',\n 'azimuth',\n 'baseFrequency',\n 'baseline-shift',\n 'bias',\n 'class',\n 'clip-path',\n 'clip-rule',\n 'clipPathUnits',\n 'color',\n 'color-interpolation-filters',\n 'cx',\n 'cy',\n 'd',\n 'diffuseConstant',\n 'display',\n 'divisor',\n 'dominant-baseline',\n 'dx',\n 'dy',\n 'edgeMode',\n 'elevation',\n 'exponent',\n 'fill',\n 'fill-opacity',\n 'fill-rule',\n 'filter',\n 'filterUnits',\n 'flood-color',\n 'flood-opacity',\n 'focusable',\n 'font-family',\n 'font-size',\n 'font-style',\n 'font-weight',\n 'fr',\n 'fx',\n 'fy',\n 'gradientTransform',\n 'gradientUnits',\n 'height',\n 'id',\n 'in',\n 'in2',\n 'intercept',\n 'k1',\n 'k2',\n 'k3',\n 'k4',\n 'kernelMatrix',\n 'lengthAdjust',\n 'letter-spacing',\n 'lighting-color',\n 'limitingConeAngle',\n 'marker-end',\n 'marker-mid',\n 'marker-start',\n 'markerHeight',\n 'markerUnits',\n 'markerWidth',\n 'mask',\n 'maskContentUnits',\n 'maskUnits',\n 'mode',\n 'numOctaves',\n 'offset',\n 'opacity',\n 'operator',\n 'order',\n 'orient',\n 'overflow',\n 'paint-order',\n 'pathLength',\n 'patternContentUnits',\n 'patternTransform',\n 'patternUnits',\n 'points',\n 'pointsAtX',\n 'pointsAtY',\n 'pointsAtZ',\n 'preserveAlpha',\n 'preserveAspectRatio',\n 'primitiveUnits',\n 'r',\n 'radius',\n 'refX',\n 'refY',\n 'result',\n 'role',\n 'rx',\n 'ry',\n 'scale',\n 'seed',\n 'shape-rendering',\n 'slope',\n 'specularConstant',\n 'specularExponent',\n 'spreadMethod',\n 'startOffset',\n 'stdDeviation',\n 'stitchTiles',\n 'stop-color',\n 'stop-opacity',\n 'stroke',\n 'stroke-dasharray',\n 'stroke-dashoffset',\n 'stroke-linecap',\n 'stroke-linejoin',\n 'stroke-miterlimit',\n 'stroke-opacity',\n 'stroke-width',\n 'style',\n 'surfaceScale',\n 'tableValues',\n 'targetX',\n 'targetY',\n 'text-anchor',\n 'text-decoration',\n 'textLength',\n 'transform',\n 'type',\n 'values',\n 'vector-effect',\n 'version',\n 'viewBox',\n 'visibility',\n 'width',\n 'word-spacing',\n 'x',\n 'x1',\n 'x2',\n 'xChannelSelector',\n 'xmlns',\n 'xmlns:xlink',\n 'y',\n 'y1',\n 'y2',\n 'yChannelSelector',\n 'z',\n]\n\nconst FRAGMENT_ONLY_ATTRIBUTES = ['href', 'xlink:href']\n\nfunction getSvgPropertyNames(attributes: readonly string[]): Set<string> {\n // Let the same parser that reads icon files tell us the hast property name\n // for each attribute, so the allowlist cannot drift from parsing.\n const markup = `<svg ${attributes.map((attribute) => `${attribute}=\"\"`).join(' ')}></svg>`\n const svg = fromHtml(markup, { fragment: true }).children[0] as Element | undefined\n\n return new Set(Object.keys(svg?.properties ?? {}))\n}\n\nconst ALLOWED_SVG_PROPERTIES = getSvgPropertyNames(ALLOWED_SVG_ATTRIBUTES)\nconst FRAGMENT_ONLY_PROPERTIES = getSvgPropertyNames(FRAGMENT_ONLY_ATTRIBUTES)\n\nconst UNSAFE_STYLE_PATTERN = /url\\s*\\(|@import|expression\\s*\\(|javascript:|\\\\|<|behavior\\s*:|-moz-binding/i\n\nfunction isSafeStyle(value: Properties[string]): boolean {\n return typeof value === 'string' && !UNSAFE_STYLE_PATTERN.test(value)\n}\n\nfunction sanitizeProperties(properties: Properties | undefined): Properties {\n const output: Properties = {}\n\n for (const [name, value] of Object.entries(properties ?? {})) {\n if (FRAGMENT_ONLY_PROPERTIES.has(name)) {\n if (typeof value === 'string' && value.trim().startsWith('#')) output[name] = value.trim()\n continue\n }\n\n if (!ALLOWED_SVG_PROPERTIES.has(name)) continue\n if (name === 'style' && !isSafeStyle(value)) continue\n\n output[name] = value\n }\n\n return output\n}\n\n/**\n * Presentation properties a `<style>` class rule may set (they are also allowed as SVG attributes).\n * Design-tool exports (Illustrator, Figma, Sketch) put their paint in such rules, for example\n * `.cls-1{fill:#0a84ff;stroke-miterlimit:10}`.\n */\nconst STYLE_RULE_PROPERTIES = [\n 'clip-rule',\n 'color',\n 'display',\n 'fill',\n 'fill-opacity',\n 'fill-rule',\n 'flood-color',\n 'flood-opacity',\n 'font-family',\n 'font-size',\n 'font-style',\n 'font-weight',\n 'letter-spacing',\n 'lighting-color',\n 'opacity',\n 'paint-order',\n 'shape-rendering',\n 'stop-color',\n 'stop-opacity',\n 'stroke',\n 'stroke-dasharray',\n 'stroke-dashoffset',\n 'stroke-linecap',\n 'stroke-linejoin',\n 'stroke-miterlimit',\n 'stroke-opacity',\n 'stroke-width',\n 'text-anchor',\n 'vector-effect',\n 'visibility',\n]\nconst STYLE_RULE_PROPERTY_NAMES = new Map(\n STYLE_RULE_PROPERTIES.map((attribute) => [attribute, [...getSvgPropertyNames([attribute])][0]]),\n)\n/**\n * A plain value: numbers and lengths (also space/comma-separated lists such as dash arrays), hex\n * colours, keywords, quoted font names, and rgb()/rgba()/hsl()/hsla() with numeric arguments.\n * Anything that can load or reference something (`url(`, other functions, escapes) is rejected.\n */\nconst SAFE_STYLE_VALUE =\n /^(?:#[0-9a-f]{3,8}|(?:rgba?|hsla?)\\([\\d\\s.,%/-]+\\)|[\\w\\s.,%\"'-]+)$/i\nconst CLASS_SELECTOR = /^\\.(-?[_a-z][\\w-]*)$/i\n\ntype StyleRule = { className: string; declarations: Array<[string, string]> }\n\nfunction collectText(node: Element): string {\n return node.children.map((child) => (child.type === 'text' ? child.value : child.type === 'element' ? collectText(child) : '')).join('')\n}\n\nfunction collectStyleText(children: readonly (ElementContent | RootContent)[]): string {\n let text = ''\n\n for (const child of children) {\n if (child.type !== 'element') continue\n if (child.tagName === 'style') text += `${collectText(child)}\\n`\n else text += collectStyleText(child.children)\n }\n\n return text\n}\n\n/** Parses only `.class[, .class] { prop: value; … }` rules with allowlisted properties and plain values. */\nfunction parseClassStyleRules(css: string): StyleRule[] {\n const rules: StyleRule[] = []\n const withoutComments = css.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n\n for (const match of withoutComments.matchAll(/([^{}]+)\\{([^{}]*)\\}/g)) {\n const selectors = match[1].split(',').map((selector) => selector.trim())\n const classNames = selectors.map((selector) => CLASS_SELECTOR.exec(selector)?.[1])\n if (classNames.some((name) => !name)) continue\n\n const declarations: Array<[string, string]> = []\n\n // Each declaration stands alone, like CSS: unsupported properties (e.g. `isolation`) and\n // unsafe values are skipped without discarding the rule's other, safe declarations.\n for (const declaration of match[2].split(';')) {\n const separator = declaration.indexOf(':')\n if (separator < 0) continue\n const property = declaration.slice(0, separator).trim().toLowerCase()\n const value = declaration.slice(separator + 1).replace(/\\s*!important\\s*$/i, '').trim()\n const propertyName = STYLE_RULE_PROPERTY_NAMES.get(property)\n\n if (!propertyName || !value || !SAFE_STYLE_VALUE.test(value)) continue\n\n declarations.push([propertyName, value])\n }\n\n if (declarations.length === 0) continue\n for (const className of classNames) rules.push({ className: className!, declarations })\n }\n\n return rules\n}\n\nfunction applyClassStyleRules(node: Element, rules: readonly StyleRule[]): void {\n const classes = toClassList(node.properties.className)\n\n // Later rules win, like the stylesheet they replace; class rules outrank presentation attributes.\n for (const rule of rules) {\n if (!classes.includes(rule.className)) continue\n for (const [name, value] of rule.declarations) node.properties[name] = value\n }\n\n for (const child of node.children) if (child.type === 'element') applyClassStyleRules(child, rules)\n}\n\nfunction sanitizeChildren(children: readonly (ElementContent | RootContent)[]): ElementContent[] {\n const output: ElementContent[] = []\n\n for (const child of children) {\n if (child.type === 'text') {\n output.push({ type: 'text', value: child.value })\n continue\n }\n\n if (child.type !== 'element') continue\n\n if (UNWRAP_SVG_TAG_NAMES.has(child.tagName)) {\n output.push(...sanitizeChildren(child.children))\n continue\n }\n\n if (!ALLOWED_SVG_TAG_NAMES.has(child.tagName)) continue\n\n output.push({\n type: 'element',\n children: sanitizeChildren(child.children),\n properties: sanitizeProperties(child.properties),\n tagName: child.tagName,\n })\n }\n\n return output\n}\n\n/**\n * Parses SVG file content and returns the sanitized first top-level `<svg>`\n * element, or `undefined` when the file has none.\n */\nexport function parseAndSanitizeSvg(content: string): Element | undefined {\n const root: Root = fromHtml(content, { fragment: true })\n const svg = root.children.find(\n (node): node is Element => node.type === 'element' && node.tagName === 'svg',\n )\n\n if (!svg) return undefined\n\n const sanitized: Element = {\n type: 'element',\n children: sanitizeChildren(svg.children),\n properties: sanitizeProperties(svg.properties),\n tagName: 'svg',\n }\n const styleRules = parseClassStyleRules(collectStyleText(svg.children))\n\n if (styleRules.length > 0) applyClassStyleRules(sanitized, styleRules)\n\n return sanitized\n}\n\nfunction toClassList(value: Properties[string]): string[] {\n if (Array.isArray(value)) return value.map(String)\n if (typeof value === 'string') return value.split(/\\s+/).filter(Boolean)\n\n return []\n}\n\n/** How a palette paints an icon (all values are validated CSS colours). */\nexport type SvgPaint = {\n /** Palette name, emitted as `data-pmd-palette`. */\n name: string\n primary?: string\n secondary?: string\n secondaryOpacity?: number\n}\n\n/** Classes that mark a duotone icon's secondary layer (Font Awesome and our own). */\nconst SECONDARY_LAYER_CLASSES = ['fa-secondary', 'pmd-icon-secondary']\n\n/** Paint values a palette may replace: real colours, not `none`, `currentColor` or `url(#…)` refs. */\nfunction isRecolorablePaint(value: unknown): boolean {\n if (typeof value !== 'string') return false\n\n const paint = value.trim().toLowerCase()\n\n return Boolean(paint) && !['currentcolor', 'inherit', 'none', 'transparent'].includes(paint) && !paint.startsWith('url(')\n}\n\nfunction recolorStyle(value: Properties[string], replacement: string | undefined): string | undefined {\n if (typeof value !== 'string') return undefined\n\n const declarations = value\n .split(';')\n .map((declaration) => declaration.trim())\n .filter(Boolean)\n .flatMap((declaration) => {\n const separator = declaration.indexOf(':')\n const property = declaration.slice(0, separator).trim().toLowerCase()\n\n if ((property === 'fill' || property === 'stroke') && isRecolorablePaint(declaration.slice(separator + 1)))\n return replacement ? [`${property}:${replacement}`] : []\n\n return [declaration]\n })\n\n return declarations.length > 0 ? declarations.join(';') : undefined\n}\n\n/**\n * Recolours a palette-painted icon in place. Explicit fill/stroke colours\n * become `currentColor` (the palette colour); the duotone secondary layer is\n * painted with `--pmd-icon-secondary` and its own subtree inherits from it.\n */\n/**\n * Elements whose colours define coverage or a paint server rather than what\n * the icon looks like (a white mask rect means \"fully visible\"). Painting\n * never touches their subtrees.\n */\nconst UNPAINTED_TAG_NAMES = new Set(['clipPath', 'filter', 'linearGradient', 'mask', 'pattern', 'radialGradient'])\n\nconst SECONDARY_PAINT = 'var(--pmd-icon-secondary, currentColor)'\n\n/**\n * Recolours a palette-painted icon in place. Explicit fill/stroke colours\n * become `currentColor` (the palette colour); inside the duotone secondary\n * layer they become the secondary colour, and the layer itself is filled\n * with it unless it draws with `fill=\"none\"`.\n */\nfunction applyPaint(node: Element, paint: SvgPaint, inSecondary: boolean): void {\n if (UNPAINTED_TAG_NAMES.has(node.tagName)) return\n\n const layerRoot = !inSecondary && toClassList(node.properties.className).some((name) => SECONDARY_LAYER_CLASSES.includes(name))\n const secondary = inSecondary || layerRoot\n const replacement = secondary ? SECONDARY_PAINT : 'currentColor'\n // Attributes cannot hold var(), so secondary colours go into the style.\n const declarations: string[] = []\n\n for (const property of ['fill', 'stroke'] as const)\n if (isRecolorablePaint(node.properties[property])) {\n if (secondary) {\n delete node.properties[property]\n declarations.push(`${property}:${SECONDARY_PAINT}`)\n } else {\n node.properties[property] = 'currentColor'\n }\n }\n\n const style = recolorStyle(node.properties.style, replacement)\n\n if (\n layerRoot &&\n node.properties.fill !== 'none' &&\n !declarations.some((declaration) => declaration.startsWith('fill:')) &&\n !/(?:^|;)\\s*fill\\s*:/.test(style ?? '')\n )\n declarations.push(`fill:${SECONDARY_PAINT}`)\n\n if (layerRoot && paint.secondaryOpacity !== undefined) node.properties.opacity = String(paint.secondaryOpacity)\n\n const combined = [style, ...declarations].filter(Boolean).join(';')\n\n if (combined) node.properties.style = combined\n else delete node.properties.style\n\n for (const child of node.children) if (child.type === 'element') applyPaint(child, paint, secondary)\n}\n\n/**\n * Returns a deep copy of a sanitized icon with the runtime class names and\n * accessibility attributes the renderer adds to every inline icon. With a\n * `paint`, the copy is recoloured with its palette (see `applyPaint`); without\n * one it is left exactly as the icon file draws it.\n */\nexport function instantiateSanitizedSvg(svg: Element, className: string, paint?: SvgPaint): Element {\n const copy = structuredClone(svg)\n const properties: Properties = {}\n const runtimeClasses = [...className.split(/\\s+/).filter(Boolean), ...(paint ? ['pmd-icon--palette'] : [])]\n let hasClass = false\n\n for (const [name, value] of Object.entries(copy.properties)) {\n if (name === 'ariaHidden' || name === 'focusable') continue\n\n if (name === 'className') {\n hasClass = true\n properties.className = [...toClassList(value), ...runtimeClasses]\n continue\n }\n\n properties[name] = value\n }\n\n if (!hasClass) properties.className = runtimeClasses\n\n properties.ariaHidden = 'true'\n properties.focusable = 'false'\n copy.properties = properties\n\n if (paint) {\n for (const child of copy.children) if (child.type === 'element') applyPaint(child, paint, false)\n\n // Icons that set no fill (Font Awesome brands, for one) would paint black.\n if (properties.fill === undefined) properties.fill = 'currentColor'\n else if (isRecolorablePaint(properties.fill)) properties.fill = 'currentColor'\n if (isRecolorablePaint(properties.stroke)) properties.stroke = 'currentColor'\n\n const declarations = [\n recolorStyle(properties.style, 'currentColor'),\n paint.primary ? `color:${paint.primary}` : undefined,\n paint.secondary ? `--pmd-icon-secondary:${paint.secondary}` : undefined,\n ].filter(Boolean)\n\n if (declarations.length > 0) properties.style = declarations.join(';')\n else delete properties.style\n properties.dataPmdPalette = paint.name\n }\n\n return copy\n}\n"],"names":["fromHtml","ALLOWED_SVG_TAG_NAMES","Set","UNWRAP_SVG_TAG_NAMES","ALLOWED_SVG_ATTRIBUTES","FRAGMENT_ONLY_ATTRIBUTES","getSvgPropertyNames","attributes","markup","map","attribute","join","svg","fragment","children","Object","keys","properties","ALLOWED_SVG_PROPERTIES","FRAGMENT_ONLY_PROPERTIES","UNSAFE_STYLE_PATTERN","isSafeStyle","value","test","sanitizeProperties","output","name","entries","has","trim","startsWith","STYLE_RULE_PROPERTIES","STYLE_RULE_PROPERTY_NAMES","Map","SAFE_STYLE_VALUE","CLASS_SELECTOR","collectText","node","child","type","collectStyleText","text","tagName","parseClassStyleRules","css","rules","withoutComments","replace","match","matchAll","selectors","split","selector","classNames","exec","some","declarations","declaration","separator","indexOf","property","slice","toLowerCase","propertyName","get","push","length","className","applyClassStyleRules","classes","toClassList","rule","includes","sanitizeChildren","parseAndSanitizeSvg","content","root","find","undefined","sanitized","styleRules","Array","isArray","String","filter","Boolean","SECONDARY_LAYER_CLASSES","isRecolorablePaint","paint","recolorStyle","replacement","flatMap","UNPAINTED_TAG_NAMES","SECONDARY_PAINT","applyPaint","inSecondary","layerRoot","secondary","style","fill","secondaryOpacity","opacity","combined","instantiateSanitizedSvg","copy","structuredClone","runtimeClasses","hasClass","ariaHidden","focusable","stroke","primary","dataPmdPalette"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,sBAAqB;AAE9C;;;;;;;;;;;;;;;;;;;;;;CAsBC,GAED,MAAMC,wBAAwB,IAAIC,IAAI;IACpC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,0EAA0E,GAC1E,MAAMC,uBAAuB,IAAID,IAAI;IAAC;CAAI;AAE1C,8DAA8D,GAC9D,MAAME,yBAAyB;IAC7B;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA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D,CAACM,MAAM,CAACC;QAET,IAAI7B,aAAaU,MAAM,GAAG,GAAGjD,WAAWiF,KAAK,GAAG1C,aAAa7C,IAAI,CAAC;aAC7D,OAAOM,WAAWiF,KAAK;QAC5BjF,WAAW+F,cAAc,GAAGxB,MAAM9D,IAAI;IACxC;IAEA,OAAO8E;AACT"}
package/dist/index.d.ts CHANGED
@@ -1,10 +1,17 @@
1
1
  import type { Plugin } from 'payload';
2
- import type { MarkdownFieldOptions, PayloadMarkdownConfig } from './types.js';
2
+ import type { MarkdownFieldOptions, PayloadMarkdownAppearanceOptions, PayloadMarkdownConfig } from './types.js';
3
3
  import { MarkdownBlock } from './blocks/MarkdownBlock/config.js';
4
4
  import { DEFAULT_CODE_LANGS } from './core/codeToHtml.js';
5
5
  import { DEFAULT_CALLOUT_THEMES, DEFAULT_CARD_THEMES, DEFAULT_CARDS_THEMES, DEFAULT_CELL_THEMES, DEFAULT_COLUMNS_THEMES, DEFAULT_DETAILS_THEMES, DEFAULT_SECTION_THEMES, DEFAULT_STEPS_THEMES, DEFAULT_TAB_THEMES, DEFAULT_TABS_THEMES, DEFAULT_TOC_THEMES } from './directives/themes.js';
6
6
  import { DEFAULT_MARKDOWN_MAX_LENGTH, markdownField } from './field/MarkdownField/config.js';
7
+ import { DEFAULT_PALETTES } from './palettes/index.js';
7
8
  export declare const payloadMarkdown: (pluginOptions?: PayloadMarkdownConfig) => Plugin;
8
- export { DEFAULT_CALLOUT_THEMES, DEFAULT_CARD_THEMES, DEFAULT_CARDS_THEMES, DEFAULT_CELL_THEMES, DEFAULT_CODE_LANGS, DEFAULT_COLUMNS_THEMES, DEFAULT_DETAILS_THEMES, DEFAULT_MARKDOWN_MAX_LENGTH, DEFAULT_SECTION_THEMES, DEFAULT_STEPS_THEMES, DEFAULT_TAB_THEMES, DEFAULT_TABS_THEMES, DEFAULT_TOC_THEMES, MarkdownBlock, markdownField, };
9
- export type { MarkdownFieldOptions, PayloadMarkdownConfig };
10
- export type { MarkdownCodeConfig, MarkdownColorScheme, MarkdownDirectiveTheme, MarkdownDirectiveThemeGroup, MarkdownDirectiveThemes, PayloadMarkdownIconPack, PayloadMarkdownIconsConfig, } from './types/core.js';
9
+ /**
10
+ * Palettes managed in the "Markdown Appearance" global (`appearance` option),
11
+ * cached per process. `MarkdownRenderer` loads them itself; pass the result as
12
+ * `runtimePalettes` to `renderMarkdown` to render with them elsewhere.
13
+ */
14
+ export { loadAppearancePalettes as loadMarkdownPalettes } from './appearance/runtime.js';
15
+ export { DEFAULT_CALLOUT_THEMES, DEFAULT_CARD_THEMES, DEFAULT_CARDS_THEMES, DEFAULT_CELL_THEMES, DEFAULT_CODE_LANGS, DEFAULT_COLUMNS_THEMES, DEFAULT_DETAILS_THEMES, DEFAULT_MARKDOWN_MAX_LENGTH, DEFAULT_PALETTES, DEFAULT_SECTION_THEMES, DEFAULT_STEPS_THEMES, DEFAULT_TAB_THEMES, DEFAULT_TABS_THEMES, DEFAULT_TOC_THEMES, MarkdownBlock, markdownField, };
16
+ export type { MarkdownFieldOptions, PayloadMarkdownAppearanceOptions, PayloadMarkdownConfig };
17
+ export type { MarkdownCodeConfig, MarkdownColorScheme, MarkdownDirectiveTheme, MarkdownDirectiveThemeGroup, MarkdownDirectiveThemes, MarkdownPalette, MarkdownPaletteColors, MarkdownPalettes, PayloadMarkdownIconPack, PayloadMarkdownIconsConfig, } from './types/core.js';
package/dist/index.js CHANGED
@@ -1,9 +1,12 @@
1
+ import { createAppearanceGlobal, resolveAppearanceOptions } from './appearance/config.js';
2
+ import { attachAppearancePayload, clearAppearance, registerAppearance } from './appearance/runtime.js';
1
3
  import { createMarkdownBlock, MarkdownBlock } from './blocks/MarkdownBlock/config.js';
2
4
  import { resolveEffectiveMarkdownBlockParams } from './blocks/MarkdownBlock/params.js';
3
5
  import { DEFAULT_CODE_LANGS } from './core/codeToHtml.js';
4
6
  import { DEFAULT_CALLOUT_THEMES, DEFAULT_CARD_THEMES, DEFAULT_CARDS_THEMES, DEFAULT_CELL_THEMES, DEFAULT_COLUMNS_THEMES, DEFAULT_DETAILS_THEMES, DEFAULT_SECTION_THEMES, DEFAULT_STEPS_THEMES, DEFAULT_TAB_THEMES, DEFAULT_TABS_THEMES, DEFAULT_TOC_THEMES } from './directives/themes.js';
5
7
  import { createEditorDirectiveConfig, PAYLOAD_MARKDOWN_ADMIN_CUSTOM_KEY } from './editor/directiveConfig.js';
6
8
  import { DEFAULT_MARKDOWN_MAX_LENGTH, markdownField } from './field/MarkdownField/config.js';
9
+ import { DEFAULT_PALETTES } from './palettes/index.js';
7
10
  import { clearPayloadMarkdownSettings, PAYLOAD_MARKDOWN_CONFIG_CUSTOM_KEY, resolveMarkdownBlockDefaults, resolveMarkdownFieldDefaults, setPayloadMarkdownSettings } from './runtime/index.js';
8
11
  function ensureMarkdownBlock(config, block) {
9
12
  const blocks = config.blocks ?? [];
@@ -135,7 +138,7 @@ function resolveCollectionInstallBehavior(collection, collectionOptions) {
135
138
  * the scope's effective block defaults.
136
139
  */ function createMarkdownBlockForScope(collectionSlug, settings) {
137
140
  const blockDefaults = resolveMarkdownBlockDefaults(collectionSlug, settings);
138
- return createMarkdownBlock(createEditorDirectiveConfig(blockDefaults), resolveEffectiveMarkdownBlockParams(blockDefaults));
141
+ return createMarkdownBlock(createEditorDirectiveConfig(blockDefaults, settings.appearanceSlug), resolveEffectiveMarkdownBlockParams(blockDefaults));
139
142
  }
140
143
  export const payloadMarkdown = (pluginOptions = {})=>(incomingConfig)=>{
141
144
  const config = {
@@ -145,8 +148,31 @@ export const payloadMarkdown = (pluginOptions = {})=>(incomingConfig)=>{
145
148
  // A disabled plugin must not leave a previous configuration's render
146
149
  // defaults active (CORE-18).
147
150
  clearPayloadMarkdownSettings();
151
+ clearAppearance();
148
152
  return config;
149
153
  }
154
+ // Opt-in runtime palettes: the "Markdown Appearance" global, readable by
155
+ // renders through the Payload instance captured at init.
156
+ const appearance = resolveAppearanceOptions(pluginOptions.appearance);
157
+ if (appearance) {
158
+ // Registered even when the app defines the global itself.
159
+ registerAppearance({
160
+ slug: appearance.slug,
161
+ ttl: appearance.cacheTtl
162
+ });
163
+ const globals = config.globals ?? [];
164
+ if (!globals.some((global)=>global.slug === appearance.slug)) config.globals = [
165
+ ...globals,
166
+ createAppearanceGlobal(appearance)
167
+ ];
168
+ const incomingOnInit = config.onInit;
169
+ config.onInit = async (payload)=>{
170
+ attachAppearancePayload(payload);
171
+ await incomingOnInit?.(payload);
172
+ };
173
+ } else {
174
+ clearAppearance();
175
+ }
150
176
  // The settings are owned by the config being built: a frozen snapshot on
151
177
  // its server-only `custom`, also registered process-wide (shared by every
152
178
  // installed copy of this package) for renderers without an explicit
@@ -169,11 +195,16 @@ export const payloadMarkdown = (pluginOptions = {})=>(incomingConfig)=>{
169
195
  const resolved = resolveCollectionInstallBehavior(collection, collectionOptions);
170
196
  let next = collection;
171
197
  if (resolved.installIntoBlocks) next = withMarkdownBlockInCollectionBlocks(next, createMarkdownBlockForScope(collection.slug, settings));
172
- if (resolved.installField) next = withMarkdownField(next, resolved.fieldName, withEditorConfig(resolved.fieldOptions, createEditorDirectiveConfig(resolveMarkdownFieldDefaults(collection.slug, settings))));
198
+ if (resolved.installField) next = withMarkdownField(next, resolved.fieldName, withEditorConfig(resolved.fieldOptions, createEditorDirectiveConfig(resolveMarkdownFieldDefaults(collection.slug, settings), settings.appearanceSlug)));
173
199
  return next;
174
200
  });
175
201
  return config;
176
202
  };
177
- export { DEFAULT_CALLOUT_THEMES, DEFAULT_CARD_THEMES, DEFAULT_CARDS_THEMES, DEFAULT_CELL_THEMES, DEFAULT_CODE_LANGS, DEFAULT_COLUMNS_THEMES, DEFAULT_DETAILS_THEMES, DEFAULT_MARKDOWN_MAX_LENGTH, DEFAULT_SECTION_THEMES, DEFAULT_STEPS_THEMES, DEFAULT_TAB_THEMES, DEFAULT_TABS_THEMES, DEFAULT_TOC_THEMES, MarkdownBlock, markdownField, };
203
+ /**
204
+ * Palettes managed in the "Markdown Appearance" global (`appearance` option),
205
+ * cached per process. `MarkdownRenderer` loads them itself; pass the result as
206
+ * `runtimePalettes` to `renderMarkdown` to render with them elsewhere.
207
+ */ export { loadAppearancePalettes as loadMarkdownPalettes } from './appearance/runtime.js';
208
+ export { DEFAULT_CALLOUT_THEMES, DEFAULT_CARD_THEMES, DEFAULT_CARDS_THEMES, DEFAULT_CELL_THEMES, DEFAULT_CODE_LANGS, DEFAULT_COLUMNS_THEMES, DEFAULT_DETAILS_THEMES, DEFAULT_MARKDOWN_MAX_LENGTH, DEFAULT_PALETTES, DEFAULT_SECTION_THEMES, DEFAULT_STEPS_THEMES, DEFAULT_TAB_THEMES, DEFAULT_TABS_THEMES, DEFAULT_TOC_THEMES, MarkdownBlock, markdownField, };
178
209
 
179
210
  //# sourceMappingURL=index.js.map