export async function resolveSvgAwsArchAssetImagesInline()

in packages/cdk-graph-plugin-diagram/src/internal/utils/svg.ts [40:122]


export async function resolveSvgAwsArchAssetImagesInline(
  svgString: string
): Promise<string> {
  let svg: svgson.INode = await svgson.parse(svgString);
  const imageDefs = new Map<string, svgson.INode>();

  svg = traverse(svg).forEach(function (this: traverse.TraverseContext, x) {
    if (typeof x === "object" && x?.type === "element") {
      const node = x as svgson.INode;
      if (node.name !== "image") {
        return;
      }

      const xlinkHref = node.attributes[XLINK_HREF];
      const isAssetPath =
        xlinkHref &&
        xlinkHref.length &&
        !(
          xlinkHref.startsWith("http") ||
          (xlinkHref.startsWith("/") &&
            !xlinkHref.startsWith(AwsArchitecture.assetDirectory))
        );

      if (isAssetPath) {
        const {
          width,
          height,
          value,
          [XLINK_HREF]: assetPath,
          ...attributes
        } = node.attributes;

        const id = AwsArchitecture.parseAssetPath(assetPath!).assetKey;

        if (!imageDefs.has(id)) {
          imageDefs.set(id, {
            type: "element",
            name: "image",
            value,
            children: [],
            attributes: {
              id,
              width,
              height,
              [XLINK_HREF]: AwsArchitecture.resolveAssetPath(assetPath),
            },
          });
        }

        const useDefNode: svgson.INode = {
          type: "element",
          name: "use",
          value,
          children: [],
          attributes: {
            ...attributes,
            [XLINK_HREF]: `#${id}`,
          },
        };

        this.update(useDefNode, true);
      }
    }
  });

  for (const [, imageDef] of imageDefs.entries()) {
    const href = imageDef.attributes[XLINK_HREF];
    imageDef.attributes[XLINK_HREF] = await encodeSvgFileDataUrl(href);
  }

  svg.children.unshift({
    type: "element",
    name: "defs",
    value: "",
    attributes: {},
    children: Array.from(imageDefs.values()),
  });

  addGraphFontCssStyles(svg);
  reconcileViewBox(svg);

  return svgson.stringify(svg);
}