markdown-artifact-images.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. const ARTIFACT_IMAGE_RENDER_PREFIX = "/__zcode_artifact_image__/";
  2. const FENCE_PATTERN = /^( {0,3})(`{3,}|~{3,})(.*)$/u;
  3. const ARTIFACT_IMAGE_PATTERN =
  4. /!\[[^\]\n]*\]\(\s*(?:<)?(zcode-artifact:\/\/[^\s)>]+)(?:>)?(?:\s+(?:"[^"]*"|'[^']*'|\([^)]*\)))?\s*\)/gu;
  5. function mapOutsideMarkdownFences(markdown: string, transform: (line: string) => string): string {
  6. let activeMarker: "`" | "~" | null = null;
  7. let activeLength = 0;
  8. return markdown
  9. .split("\n")
  10. .map((line) => {
  11. const fence = line.match(FENCE_PATTERN);
  12. if (fence?.[2]) {
  13. const run = fence[2];
  14. const marker = run[0] as "`" | "~";
  15. const suffix = fence[3] ?? "";
  16. if (activeMarker === marker && run.length >= activeLength && suffix.trim() === "") {
  17. activeMarker = null;
  18. activeLength = 0;
  19. } else if (!activeMarker && (marker === "~" || !suffix.includes("`"))) {
  20. activeMarker = marker;
  21. activeLength = run.length;
  22. }
  23. return line;
  24. }
  25. return activeMarker ? line : transform(line);
  26. })
  27. .join("\n");
  28. }
  29. export function extractMarkdownArtifactImageRefs(markdown: string): string[] {
  30. const refs = new Set<string>();
  31. mapOutsideMarkdownFences(markdown, (line) => {
  32. for (const match of line.matchAll(ARTIFACT_IMAGE_PATTERN)) {
  33. if (match[1]) refs.add(match[1]);
  34. }
  35. return line;
  36. });
  37. return [...refs];
  38. }
  39. export function rewriteMarkdownArtifactImageSources(markdown: string): string {
  40. return mapOutsideMarkdownFences(markdown, (line) =>
  41. line.replace(ARTIFACT_IMAGE_PATTERN, (image, ref: string) =>
  42. image.replace(ref, `${ARTIFACT_IMAGE_RENDER_PREFIX}${encodeURIComponent(ref)}`),
  43. ),
  44. );
  45. }
  46. export function decodeMarkdownArtifactImageSource(source: string): string | null {
  47. if (!source.startsWith(ARTIFACT_IMAGE_RENDER_PREFIX)) return null;
  48. try {
  49. const ref = decodeURIComponent(source.slice(ARTIFACT_IMAGE_RENDER_PREFIX.length));
  50. return ref.startsWith("zcode-artifact://") ? ref : null;
  51. } catch {
  52. return null;
  53. }
  54. }