UNPKG

@mui/internal-docs-infra

Version:

MUI Infra - internal documentation creation tools.

75 lines (70 loc) 2.8 kB
import _createForOfIteratorHelper from "@babel/runtime/helpers/esm/createForOfIteratorHelper"; import { patch, clone } from 'jsondiffpatch'; /** * Applies a specific transform to a variant source and returns the transformed source * @param source - The original variant source (string, HastNodes, or hastJson object) * @param transforms - Object containing all available transforms * @param transformKey - The key of the specific transform to apply * @returns The transformed variant source in the same format as the input * @throws Error if the transform key doesn't exist or patching fails */ export function applyTransform(source, transforms, transformKey) { var transform = transforms[transformKey]; if (!transform) { throw new Error("Transform \"".concat(transformKey, "\" not found in transforms")); } // Determine the format of the source and apply the appropriate transform strategy if (typeof source === 'string') { // For string sources, deltas are typically line-array based (from transformSource) var sourceLines = source.split('\n'); var patched = patch(sourceLines, transform.delta); if (!Array.isArray(patched)) { throw new Error("Patch for transform \"".concat(transformKey, "\" did not return an array")); } return patched.join('\n'); } // For Hast node sources, deltas are typically node-based (from transformParsedSource) var sourceRoot; var isHastJson = 'hastJson' in source; if (isHastJson) { sourceRoot = JSON.parse(source.hastJson); } else { sourceRoot = source; } // Apply the node-based delta var patchedNodes = patch(clone(sourceRoot), transform.delta); if (!patchedNodes) { throw new Error("Patch for transform \"".concat(transformKey, "\" returned null/undefined")); } // Return in the same format as the input if (isHastJson) { return { hastJson: JSON.stringify(patchedNodes) }; } return patchedNodes; } /** * Applies multiple transforms to a variant source in sequence * @param source - The original variant source * @param transforms - Object containing all available transforms * @param transformKeys - Array of transform keys to apply in order * @returns The transformed variant source in the same format as the input * @throws Error if any transform key doesn't exist or patching fails */ export function applyTransforms(source, transforms, transformKeys) { var currentSource = source; var _iterator = _createForOfIteratorHelper(transformKeys), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var transformKey = _step.value; currentSource = applyTransform(currentSource, transforms, transformKey); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return currentSource; }