@mui/internal-docs-infra
Version:
MUI Infra - internal documentation creation tools.
1,083 lines (1,055 loc) • 46.7 kB
JavaScript
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _regeneratorRuntime from "@babel/runtime/helpers/esm/regeneratorRuntime";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _createForOfIteratorHelper from "@babel/runtime/helpers/esm/createForOfIteratorHelper";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import { transformSource } from "./transformSource.js";
import { transformParsedSource } from "./transformParsedSource.js";
import { getFileNameFromUrl } from "../pipeline/loaderUtils/index.js";
import { mergeExternals } from "../pipeline/loaderUtils/mergeExternals.js";
/**
* Generate a conflict-free filename for globalsCode files.
* Strategy:
* 1. Try original filename
* 2. If conflict, try "global_" prefix
* 3. If still conflict, add numbers: "global_filename_1.ext", "global_filename_2.ext", etc.
*/
function generateConflictFreeFilename(originalFilename, existingFiles) {
// First try the original filename
if (!existingFiles.has(originalFilename)) {
return originalFilename;
}
// Try with global_ prefix
var globalFilename = "global_".concat(originalFilename);
if (!existingFiles.has(globalFilename)) {
return globalFilename;
}
// Split filename into name and extension for proper numbering
var lastDotIndex = originalFilename.lastIndexOf('.');
var nameWithoutExt;
var extension;
if (lastDotIndex === -1 || lastDotIndex === 0) {
// No extension or starts with dot (hidden file)
nameWithoutExt = originalFilename;
extension = '';
} else {
nameWithoutExt = originalFilename.substring(0, lastDotIndex);
extension = originalFilename.substring(lastDotIndex); // includes the dot
}
// Add numbers until we find a free name, preserving extension
var counter = 1;
var candidateName;
do {
candidateName = "global_".concat(nameWithoutExt, "_").concat(counter).concat(extension);
counter += 1;
} while (existingFiles.has(candidateName));
return candidateName;
}
// Helper function to check if we're in production
function isProduction() {
return typeof process !== 'undefined' && process.env.NODE_ENV === 'production';
}
// Helper function to convert a nested key based on the directory of the source file key
function convertKeyBasedOnDirectory(nestedKey, sourceFileKey) {
// If it's an absolute path (starts with / or contains ://), keep as-is
if (nestedKey.startsWith('/') || nestedKey.includes('://')) {
return nestedKey;
}
// Treat bare filenames as relative to current directory (same as ./filename)
var processedNestedKey = nestedKey;
if (!nestedKey.startsWith('.')) {
processedNestedKey = "./".concat(nestedKey);
}
// Manual path resolution: resolve processedNestedKey relative to the directory of sourceFileKey
// Both paths are relative to the entry directory (which is always './') - ignore file:// URLs completely
// Get the directory of the source file key (not URL)
var sourceDir = sourceFileKey.includes('/') ? sourceFileKey.substring(0, sourceFileKey.lastIndexOf('/')) : '.';
// Parse both paths into components
var parsePathComponents = function parsePathComponents(path) {
if (path === '.' || path === '') {
return [];
}
return path.split('/').filter(function (part) {
return part !== '';
});
};
var sourceDirComponents = parsePathComponents(sourceDir);
var nestedComponents = parsePathComponents(processedNestedKey);
// Start from the source directory and apply the nested path
var resultComponents = _toConsumableArray(sourceDirComponents);
// Apply each component of the nested path
var _iterator = _createForOfIteratorHelper(nestedComponents),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var component = _step.value;
if (component === '..') {
if (resultComponents.length > 0 && resultComponents[resultComponents.length - 1] !== '..') {
// Normal case: pop a regular directory component
resultComponents.pop();
} else {
// Either resultComponents is empty OR the last component is already '..'
// In both cases, we need to go up one more level
resultComponents.push('..');
}
} else if (component === '.') {
// Current directory, skip
continue;
} else {
resultComponents.push(component);
}
}
// Build the final result
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
if (resultComponents.length === 0) {
return '';
}
var result = resultComponents.join('/');
return result;
}
/**
* Normalize a relative path key by removing unnecessary ./ prefix
*/
function normalizePathKey(key) {
if (key.startsWith('./')) {
return key.substring(2);
}
return key;
}
/**
* Loads and processes extra files recursively with support for relative paths
* and circular dependency detection. Uses Promise.all for parallel loading.
*/
function loadSingleFile(_x, _x2, _x3, _x4, _x5, _x6, _x7, _x8, _x9) {
return _loadSingleFile.apply(this, arguments);
}
/**
* Loads and processes extra files recursively with support for relative paths
* and circular dependency detection. Uses Promise.all for parallel loading.
*/
function _loadSingleFile() {
_loadSingleFile = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(variantName, fileName, source, url, loadSource, sourceParser, sourceTransformers, loadSourceCache, transforms) {
var options,
allFilesListed,
knownExtraFiles,
_options$disableTrans,
disableTransforms,
_options$disableParsi,
disableParsing,
finalSource,
extraFilesFromSource,
extraDependenciesFromSource,
externalsFromSource,
loadPromise,
loadResult,
_i,
_Object$entries,
_Object$entries$_i,
extraFileName,
fileData,
_iterator2,
_step2,
dependency,
newFiles,
_i2,
_Object$keys,
extraFileKey,
message,
finalTransforms,
sourceString,
parseSource,
_args = arguments;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
options = _args.length > 9 && _args[9] !== undefined ? _args[9] : {};
allFilesListed = _args.length > 10 && _args[10] !== undefined ? _args[10] : false;
knownExtraFiles = _args.length > 11 && _args[11] !== undefined ? _args[11] : new Set();
_options$disableTrans = options.disableTransforms, disableTransforms = _options$disableTrans === void 0 ? false : _options$disableTrans, _options$disableParsi = options.disableParsing, disableParsing = _options$disableParsi === void 0 ? false : _options$disableParsi;
finalSource = source;
if (finalSource) {
_context.next = 68;
break;
}
if (loadSource) {
_context.next = 8;
break;
}
throw new Error('"loadSource" function is required when source is not provided');
case 8:
if (url) {
_context.next = 10;
break;
}
throw new Error('URL is required when loading source');
case 10:
_context.prev = 10;
// Check cache first to avoid duplicate loadSource calls
loadPromise = loadSourceCache.get(url);
if (!loadPromise) {
loadPromise = loadSource(url);
loadSourceCache.set(url, loadPromise);
}
_context.next = 15;
return loadPromise;
case 15:
loadResult = _context.sent;
finalSource = loadResult.source;
extraFilesFromSource = loadResult.extraFiles;
extraDependenciesFromSource = loadResult.extraDependencies;
externalsFromSource = loadResult.externals;
// Validate that extraFiles from loadSource contain only absolute URLs as values
if (!extraFilesFromSource) {
_context.next = 31;
break;
}
_i = 0, _Object$entries = Object.entries(extraFilesFromSource);
case 22:
if (!(_i < _Object$entries.length)) {
_context.next = 31;
break;
}
_Object$entries$_i = _slicedToArray(_Object$entries[_i], 2), extraFileName = _Object$entries$_i[0], fileData = _Object$entries$_i[1];
if (!(extraFileName.includes('://') || extraFileName.startsWith('/'))) {
_context.next = 26;
break;
}
throw new Error("Invalid extraFiles from loadSource: key \"".concat(extraFileName, "\" appears to be an absolute path. ") + "extraFiles keys should be relative paths from the current file.");
case 26:
if (!(typeof fileData === 'string' && fileData.startsWith('.'))) {
_context.next = 28;
break;
}
throw new Error("Invalid extraFiles from loadSource: \"".concat(extraFileName, "\" has relative path \"").concat(fileData, "\". ") + "All extraFiles values must be absolute URLs.");
case 28:
_i++;
_context.next = 22;
break;
case 31:
if (!extraDependenciesFromSource) {
_context.next = 51;
break;
}
_iterator2 = _createForOfIteratorHelper(extraDependenciesFromSource);
_context.prev = 33;
_iterator2.s();
case 35:
if ((_step2 = _iterator2.n()).done) {
_context.next = 43;
break;
}
dependency = _step2.value;
if (!dependency.startsWith('.')) {
_context.next = 39;
break;
}
throw new Error("Invalid extraDependencies from loadSource: \"".concat(dependency, "\" is a relative path. ") + "All extraDependencies must be absolute URLs.");
case 39:
if (!(dependency === url)) {
_context.next = 41;
break;
}
throw new Error("Invalid extraDependencies from loadSource: \"".concat(dependency, "\" is the same as the input URL. ") + "extraDependencies should not include the file being loaded.");
case 41:
_context.next = 35;
break;
case 43:
_context.next = 48;
break;
case 45:
_context.prev = 45;
_context.t0 = _context["catch"](33);
_iterator2.e(_context.t0);
case 48:
_context.prev = 48;
_iterator2.f();
return _context.finish(48);
case 51:
if (!(allFilesListed && (extraFilesFromSource || extraDependenciesFromSource))) {
_context.next = 61;
break;
}
newFiles = [];
if (extraFilesFromSource) {
// Check if any extraFiles keys are not in the known set
for (_i2 = 0, _Object$keys = Object.keys(extraFilesFromSource); _i2 < _Object$keys.length; _i2++) {
extraFileKey = _Object$keys[_i2];
if (!knownExtraFiles.has(extraFileKey)) {
newFiles.push(extraFileKey);
}
}
}
if (!(newFiles.length > 0)) {
_context.next = 61;
break;
}
message = "Unexpected files discovered via loadSource when allFilesListed=true (variant: ".concat(variantName, ", file: ").concat(fileName, "). ") + "New files: ".concat(newFiles.join(', '), ". ") + "Please update the loadVariantMeta function to provide the complete list of files upfront.";
if (!isProduction()) {
_context.next = 60;
break;
}
console.warn(message);
_context.next = 61;
break;
case 60:
throw new Error(message);
case 61:
_context.next = 68;
break;
case 63:
_context.prev = 63;
_context.t1 = _context["catch"](10);
if (!(_context.t1 instanceof Error && (_context.t1.message.startsWith('Invalid extraFiles from loadSource:') || _context.t1.message.startsWith('Invalid extraDependencies from loadSource:') || _context.t1.message.startsWith('Unexpected files discovered via loadSource when allFilesListed=true')))) {
_context.next = 67;
break;
}
throw _context.t1;
case 67:
throw new Error("Failed to load source code (variant: ".concat(variantName, ", file: ").concat(fileName, ", url: ").concat(url, "): ").concat(JSON.stringify(_context.t1)));
case 68:
// Apply source transformers if no transforms exist and transforms are not disabled
finalTransforms = transforms;
if (!(sourceTransformers && !finalTransforms && !disableTransforms && finalSource)) {
_context.next = 73;
break;
}
_context.next = 72;
return transformSource(finalSource, normalizePathKey(fileName), sourceTransformers);
case 72:
finalTransforms = _context.sent;
case 73:
if (!(typeof finalSource === 'string' && !disableParsing)) {
_context.next = 91;
break;
}
if (sourceParser) {
_context.next = 76;
break;
}
throw new Error('"sourceParser" function is required when source is a string and parsing is not disabled');
case 76:
_context.prev = 76;
sourceString = finalSource;
_context.next = 80;
return sourceParser;
case 80:
parseSource = _context.sent;
finalSource = parseSource(finalSource, fileName);
if (!(finalTransforms && !disableTransforms)) {
_context.next = 86;
break;
}
_context.next = 85;
return transformParsedSource(sourceString, finalSource, normalizePathKey(fileName), finalTransforms, parseSource);
case 85:
finalTransforms = _context.sent;
case 86:
_context.next = 91;
break;
case 88:
_context.prev = 88;
_context.t2 = _context["catch"](76);
throw new Error("Failed to parse source code (variant: ".concat(variantName, ", file: ").concat(fileName, ", url: ").concat(url, "): ").concat(_context.t2 instanceof Error ? _context.t2.message : ''));
case 91:
return _context.abrupt("return", {
source: finalSource,
transforms: finalTransforms,
extraFiles: extraFilesFromSource,
extraDependencies: extraDependenciesFromSource,
externals: externalsFromSource
});
case 92:
case "end":
return _context.stop();
}
}, _callee, null, [[10, 63], [33, 45, 48, 51], [76, 88]]);
}));
return _loadSingleFile.apply(this, arguments);
}
function loadExtraFiles(_x0, _x1, _x10, _x11, _x12, _x13, _x14, _x15) {
return _loadExtraFiles.apply(this, arguments);
}
/**
* Loads a variant with support for recursive extra file loading.
* The loadSource function can now return extraFiles that will be loaded recursively.
* Supports both relative and absolute paths for extra files.
* Uses Promise.all for efficient parallel loading of extra files.
*/
function _loadExtraFiles() {
_loadExtraFiles = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(variantName, extraFiles, baseUrl, entryUrl,
// Track the original entry file URL
loadSource, sourceParser, sourceTransformers, loadSourceCache) {
var options,
allFilesListed,
knownExtraFiles,
globalsFileKeys,
_options$maxDepth,
maxDepth,
_options$loadedFiles,
loadedFiles,
processedExtraFiles,
allFilesUsed,
allExternals,
extraFilePromises,
extraFileResults,
nestedExtraFilesPromises,
_iterator3,
_step3,
_loop,
nestedExtraFilesResults,
_iterator4,
_step4,
_step4$value,
nestedExtraFiles,
nestedFilesUsed,
nestedExternals,
sourceFileKey,
mergedNestedExternals,
_i3,
_Object$entries2,
_Object$entries2$_i,
nestedKey,
nestedValue,
convertedKey,
normalizedConvertedKey,
_args4 = arguments;
return _regeneratorRuntime().wrap(function _callee3$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
options = _args4.length > 8 && _args4[8] !== undefined ? _args4[8] : {};
allFilesListed = _args4.length > 9 && _args4[9] !== undefined ? _args4[9] : false;
knownExtraFiles = _args4.length > 10 && _args4[10] !== undefined ? _args4[10] : new Set();
globalsFileKeys = _args4.length > 11 && _args4[11] !== undefined ? _args4[11] : new Set();
_options$maxDepth = options.maxDepth, maxDepth = _options$maxDepth === void 0 ? 10 : _options$maxDepth, _options$loadedFiles = options.loadedFiles, loadedFiles = _options$loadedFiles === void 0 ? new Set() : _options$loadedFiles;
if (!(maxDepth <= 0)) {
_context4.next = 7;
break;
}
throw new Error('Maximum recursion depth reached while loading extra files');
case 7:
processedExtraFiles = {};
allFilesUsed = [];
allExternals = {}; // Start loading all extra files in parallel
extraFilePromises = Object.entries(extraFiles).map(/*#__PURE__*/function () {
var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref) {
var _ref3, fileName, fileData, fileUrl, sourceData, transforms, fileResult, filesUsedFromFile, externalsFromFile;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
_ref3 = _slicedToArray(_ref, 2), fileName = _ref3[0], fileData = _ref3[1];
_context2.prev = 1;
if (!(typeof fileData === 'string')) {
_context2.next = 9;
break;
}
// fileData is a URL/path - use it directly, don't modify it
fileUrl = fileData;
// Check for circular dependencies
if (!loadedFiles.has(fileUrl)) {
_context2.next = 6;
break;
}
throw new Error("Circular dependency detected: ".concat(fileUrl));
case 6:
loadedFiles.add(fileUrl);
_context2.next = 12;
break;
case 9:
// fileData is an object with source and/or transforms
sourceData = fileData.source;
transforms = fileData.transforms;
fileUrl = baseUrl; // Use base URL as fallback
case 12:
_context2.next = 14;
return loadSingleFile(variantName, fileName, sourceData, fileUrl, loadSource, sourceParser, sourceTransformers, loadSourceCache, transforms, _objectSpread(_objectSpread({}, options), {}, {
maxDepth: maxDepth - 1,
loadedFiles: new Set(loadedFiles)
}), allFilesListed, knownExtraFiles);
case 14:
fileResult = _context2.sent;
// Collect files used from this file load
filesUsedFromFile = [];
if (typeof fileData === 'string') {
filesUsedFromFile.push(fileUrl);
}
if (fileResult.extraDependencies) {
filesUsedFromFile.push.apply(filesUsedFromFile, _toConsumableArray(fileResult.extraDependencies));
}
// Collect externals from this file load
externalsFromFile = {};
if (fileResult.externals) {
Object.assign(externalsFromFile, fileResult.externals);
}
return _context2.abrupt("return", {
fileName: fileName,
result: fileResult,
filesUsed: filesUsedFromFile,
externals: externalsFromFile
});
case 23:
_context2.prev = 23;
_context2.t0 = _context2["catch"](1);
throw new Error("Failed to load extra file (variant: ".concat(variantName, ", file: ").concat(fileName, ", url: ").concat(baseUrl, "): ").concat(_context2.t0 instanceof Error ? _context2.t0.message : ''));
case 26:
case "end":
return _context2.stop();
}
}, _callee2, null, [[1, 23]]);
}));
return function (_x23) {
return _ref2.apply(this, arguments);
};
}()); // Wait for all extra files to load
_context4.next = 13;
return Promise.all(extraFilePromises);
case 13:
extraFileResults = _context4.sent;
// Process results and handle nested extra files
nestedExtraFilesPromises = [];
_iterator3 = _createForOfIteratorHelper(extraFileResults);
_context4.prev = 16;
_loop = /*#__PURE__*/_regeneratorRuntime().mark(function _loop() {
var _step3$value, fileName, result, filesUsed, externals, normalizedFileName, originalFileData, metadata, mergedExternals, sourceFileUrl, fileData;
return _regeneratorRuntime().wrap(function _loop$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
_step3$value = _step3.value, fileName = _step3$value.fileName, result = _step3$value.result, filesUsed = _step3$value.filesUsed, externals = _step3$value.externals;
normalizedFileName = normalizePathKey(fileName);
originalFileData = extraFiles[fileName]; // Preserve metadata flag if it exists in the original data, or if this file came from globals
if (typeof originalFileData !== 'string') {
metadata = originalFileData.metadata;
} else if (globalsFileKeys.has(fileName)) {
metadata = true;
}
processedExtraFiles[normalizedFileName] = _objectSpread({
source: result.source,
transforms: result.transforms
}, metadata !== undefined && {
metadata: metadata
});
// Add files used from this file load
allFilesUsed.push.apply(allFilesUsed, _toConsumableArray(filesUsed));
// Add externals from this file load using proper merging
mergedExternals = mergeExternals([allExternals, externals]);
Object.assign(allExternals, mergedExternals);
// Collect promises for nested extra files with their source key
if (result.extraFiles) {
sourceFileUrl = baseUrl;
fileData = extraFiles[fileName];
if (typeof fileData === 'string') {
sourceFileUrl = fileData; // Use the URL directly, don't modify it
}
nestedExtraFilesPromises.push(loadExtraFiles(variantName, result.extraFiles, sourceFileUrl,
// Use the source file's URL as base for its extra files
entryUrl,
// Keep the entry URL for final conversion
loadSource, sourceParser, sourceTransformers, loadSourceCache, _objectSpread(_objectSpread({}, options), {}, {
maxDepth: maxDepth - 1,
loadedFiles: new Set(loadedFiles)
}), allFilesListed, knownExtraFiles, globalsFileKeys // Pass through globals file tracking
).then(function (nestedResult) {
return {
files: nestedResult.extraFiles,
allFilesUsed: nestedResult.allFilesUsed,
allExternals: nestedResult.allExternals,
sourceFileKey: normalizedFileName // Pass the normalized key
};
}));
}
case 9:
case "end":
return _context3.stop();
}
}, _loop);
});
_iterator3.s();
case 19:
if ((_step3 = _iterator3.n()).done) {
_context4.next = 23;
break;
}
return _context4.delegateYield(_loop(), "t0", 21);
case 21:
_context4.next = 19;
break;
case 23:
_context4.next = 28;
break;
case 25:
_context4.prev = 25;
_context4.t1 = _context4["catch"](16);
_iterator3.e(_context4.t1);
case 28:
_context4.prev = 28;
_iterator3.f();
return _context4.finish(28);
case 31:
if (!(nestedExtraFilesPromises.length > 0)) {
_context4.next = 37;
break;
}
_context4.next = 34;
return Promise.all(nestedExtraFilesPromises);
case 34:
nestedExtraFilesResults = _context4.sent;
_iterator4 = _createForOfIteratorHelper(nestedExtraFilesResults);
try {
for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
_step4$value = _step4.value, nestedExtraFiles = _step4$value.files, nestedFilesUsed = _step4$value.allFilesUsed, nestedExternals = _step4$value.allExternals, sourceFileKey = _step4$value.sourceFileKey;
// Add nested files used
allFilesUsed.push.apply(allFilesUsed, _toConsumableArray(nestedFilesUsed));
// Add nested externals using proper merging
mergedNestedExternals = mergeExternals([allExternals, nestedExternals]);
Object.assign(allExternals, mergedNestedExternals);
for (_i3 = 0, _Object$entries2 = Object.entries(nestedExtraFiles); _i3 < _Object$entries2.length; _i3++) {
_Object$entries2$_i = _slicedToArray(_Object$entries2[_i3], 2), nestedKey = _Object$entries2$_i[0], nestedValue = _Object$entries2$_i[1];
// Convert the key based on the directory structure of the source key
convertedKey = convertKeyBasedOnDirectory(nestedKey, sourceFileKey);
normalizedConvertedKey = normalizePathKey(convertedKey);
processedExtraFiles[normalizedConvertedKey] = nestedValue;
}
}
} catch (err) {
_iterator4.e(err);
} finally {
_iterator4.f();
}
case 37:
return _context4.abrupt("return", {
extraFiles: processedExtraFiles,
allFilesUsed: allFilesUsed,
allExternals: allExternals
});
case 38:
case "end":
return _context4.stop();
}
}, _callee3, null, [[16, 25, 28, 31]]);
}));
return _loadExtraFiles.apply(this, arguments);
}
export function loadVariant(_x16, _x17, _x18, _x19, _x20, _x21, _x22) {
return _loadVariant.apply(this, arguments);
}
function _loadVariant() {
_loadVariant = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(url, variantName, variant, sourceParser, loadSource, loadVariantMeta, sourceTransformers) {
var options,
globalsCode,
loadSourceCache,
_getFileNameFromUrl,
_fileName,
loadedFiles,
allFilesUsed,
allExternals,
knownExtraFiles,
_i4,
_Object$keys2,
extraFileName,
fileName,
_finalVariant,
mainFileResult,
allExtraFiles,
_i5,
_Object$keys3,
_extraFileName,
extraFilesToLoad,
globalsFileKeys,
existingFiles,
_i6,
_Object$keys4,
key,
globalsPromises,
globalsResults,
_iterator5,
_step5,
globalsResult,
_i7,
_Object$entries3,
_Object$entries3$_i,
_key,
value,
conflictFreeKey,
loadableFiles,
_i8,
_Object$entries4,
_Object$entries4$_i,
_key2,
_value,
_i9,
_Object$entries5,
_Object$entries5$_i,
_key3,
_value2,
metadata,
urlFilesToLoad,
_i0,
_Object$entries6,
_Object$entries6$_i,
_key4,
_value3,
extraFilesResult,
_extraFilesResult,
finalVariant,
_args6 = arguments;
return _regeneratorRuntime().wrap(function _callee5$(_context6) {
while (1) switch (_context6.prev = _context6.next) {
case 0:
options = _args6.length > 7 && _args6[7] !== undefined ? _args6[7] : {};
if (variant) {
_context6.next = 3;
break;
}
throw new Error("Variant is missing from code: ".concat(variantName));
case 3:
globalsCode = options.globalsCode; // Create a cache for loadSource calls scoped to this loadVariant call
loadSourceCache = new Map();
if (!(typeof variant === 'string')) {
_context6.next = 22;
break;
}
if (loadVariantMeta) {
_context6.next = 13;
break;
}
// Create a basic loadVariantMeta function as fallback
_getFileNameFromUrl = getFileNameFromUrl(variant), _fileName = _getFileNameFromUrl.fileName;
if (_fileName) {
_context6.next = 10;
break;
}
throw new Error("Cannot determine fileName from URL \"".concat(variant, "\" for variant \"").concat(variantName, "\". ") + "Please provide a loadVariantMeta function or ensure the URL has a valid file extension.");
case 10:
variant = {
url: variant,
fileName: _fileName
};
_context6.next = 22;
break;
case 13:
_context6.prev = 13;
_context6.next = 16;
return loadVariantMeta(variantName, variant);
case 16:
variant = _context6.sent;
_context6.next = 22;
break;
case 19:
_context6.prev = 19;
_context6.t0 = _context6["catch"](13);
throw new Error("Failed to load variant code (variant: ".concat(variantName, ", url: ").concat(variant, "): ").concat(JSON.stringify(_context6.t0)));
case 22:
loadedFiles = new Set();
if (url) {
loadedFiles.add(url);
}
allFilesUsed = url ? [url] : []; // Start with the main file URL if available
allExternals = {}; // Collect externals from all sources
// Build set of known extra files from variant definition
knownExtraFiles = new Set();
if (variant.extraFiles) {
for (_i4 = 0, _Object$keys2 = Object.keys(variant.extraFiles); _i4 < _Object$keys2.length; _i4++) {
extraFileName = _Object$keys2[_i4];
knownExtraFiles.add(extraFileName);
}
}
// Load main file
fileName = variant.fileName || (url ? getFileNameFromUrl(url).fileName : undefined); // If we don't have a fileName and no URL, we can't parse or transform but can still return the code
if (!(!fileName && !url)) {
_context6.next = 32;
break;
}
// Return the variant as-is without parsing or transforms
_finalVariant = _objectSpread(_objectSpread({}, variant), {}, {
source: typeof variant.source === 'string' ? {
type: 'root',
children: [{
type: 'text',
value: variant.source || ''
}]
} : variant.source
});
return _context6.abrupt("return", {
code: _finalVariant,
dependencies: [],
// No dependencies without URL
externals: {} // No externals without URL
});
case 32:
if (fileName) {
_context6.next = 34;
break;
}
throw new Error("No fileName available for variant \"".concat(variantName, "\". ") + "Please provide a fileName in the variant definition or ensure the URL has a valid file extension.");
case 34:
_context6.next = 36;
return loadSingleFile(variantName, fileName, variant.source, url, loadSource, sourceParser, sourceTransformers, loadSourceCache, variant.transforms, _objectSpread(_objectSpread({}, options), {}, {
loadedFiles: loadedFiles
}), variant.allFilesListed || false, knownExtraFiles);
case 36:
mainFileResult = _context6.sent;
// Add files used from main file loading
if (mainFileResult.extraDependencies) {
allFilesUsed.push.apply(allFilesUsed, _toConsumableArray(mainFileResult.extraDependencies));
}
// Add externals from main file loading
if (mainFileResult.externals) {
allExternals = mergeExternals([allExternals, mainFileResult.externals]);
}
allExtraFiles = {}; // Validate extraFiles keys from variant definition
if (!variant.extraFiles) {
_context6.next = 49;
break;
}
_i5 = 0, _Object$keys3 = Object.keys(variant.extraFiles);
case 42:
if (!(_i5 < _Object$keys3.length)) {
_context6.next = 49;
break;
}
_extraFileName = _Object$keys3[_i5];
if (!(_extraFileName.includes('://') || _extraFileName.startsWith('/'))) {
_context6.next = 46;
break;
}
throw new Error("Invalid extraFiles key in variant: \"".concat(_extraFileName, "\" appears to be an absolute path. ") + "extraFiles keys in variant definition should be relative paths from the main file.");
case 46:
_i5++;
_context6.next = 42;
break;
case 49:
// Collect extra files from variant definition and from loaded source
extraFilesToLoad = _objectSpread(_objectSpread({}, variant.extraFiles || {}), mainFileResult.extraFiles || {}); // Track which files come from globals for metadata marking
globalsFileKeys = new Set(); // Track globals file keys for loadExtraFiles
// Process globalsCode array and add to extraFiles if provided
if (!(globalsCode && globalsCode.length > 0)) {
_context6.next = 61;
break;
}
// Collect existing filenames to avoid conflicts
existingFiles = new Set(); // Add main variant filename if it exists
if (variant.fileName) {
existingFiles.add(variant.fileName);
}
// Add already loaded extra files
for (_i6 = 0, _Object$keys4 = Object.keys(extraFilesToLoad); _i6 < _Object$keys4.length; _i6++) {
key = _Object$keys4[_i6];
existingFiles.add(key);
}
// Process all globals items in parallel
globalsPromises = globalsCode.map(/*#__PURE__*/function () {
var _ref4 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(globalsItem) {
var globalsVariant, _getFileNameFromUrl2, globalsFileName, globalsResult;
return _regeneratorRuntime().wrap(function _callee4$(_context5) {
while (1) switch (_context5.prev = _context5.next) {
case 0:
if (!(typeof globalsItem === 'string')) {
_context5.next = 19;
break;
}
if (loadVariantMeta) {
_context5.next = 8;
break;
}
// Create a basic variant as fallback
_getFileNameFromUrl2 = getFileNameFromUrl(globalsItem), globalsFileName = _getFileNameFromUrl2.fileName;
if (globalsFileName) {
_context5.next = 5;
break;
}
throw new Error("Cannot determine fileName from globalsCode URL \"".concat(globalsItem, "\". ") + "Please provide a loadVariantMeta function or ensure the URL has a valid file extension.");
case 5:
globalsVariant = {
url: globalsItem,
fileName: globalsFileName
};
_context5.next = 17;
break;
case 8:
_context5.prev = 8;
_context5.next = 11;
return loadVariantMeta(variantName, globalsItem);
case 11:
globalsVariant = _context5.sent;
_context5.next = 17;
break;
case 14:
_context5.prev = 14;
_context5.t0 = _context5["catch"](8);
throw new Error("Failed to load globalsCode variant metadata (variant: ".concat(variantName, ", url: ").concat(globalsItem, "): ").concat(JSON.stringify(_context5.t0)));
case 17:
_context5.next = 20;
break;
case 19:
globalsVariant = globalsItem;
case 20:
_context5.prev = 20;
_context5.next = 23;
return loadVariant(globalsVariant.url, variantName, globalsVariant, sourceParser, loadSource, loadVariantMeta, sourceTransformers, _objectSpread(_objectSpread({}, options), {}, {
globalsCode: undefined
}) // Prevent infinite recursion
);
case 23:
globalsResult = _context5.sent;
return _context5.abrupt("return", globalsResult);
case 27:
_context5.prev = 27;
_context5.t1 = _context5["catch"](20);
throw new Error("Failed to load globalsCode (variant: ".concat(variantName, "): ").concat(_context5.t1 instanceof Error ? _context5.t1.message : JSON.stringify(_context5.t1)));
case 30:
case "end":
return _context5.stop();
}
}, _callee4, null, [[8, 14], [20, 27]]);
}));
return function (_x24) {
return _ref4.apply(this, arguments);
};
}()); // Wait for all globals to load
_context6.next = 58;
return Promise.all(globalsPromises);
case 58:
globalsResults = _context6.sent;
// Merge results from all globals
_iterator5 = _createForOfIteratorHelper(globalsResults);
try {
for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
globalsResult = _step5.value;
// Add globals extraFiles (but NOT the main file)
if (globalsResult.code.extraFiles) {
// Add globals extra files with conflict-free naming and metadata flag
for (_i7 = 0, _Object$entries3 = Object.entries(globalsResult.code.extraFiles); _i7 < _Object$entries3.length; _i7++) {
_Object$entries3$_i = _slicedToArray(_Object$entries3[_i7], 2), _key = _Object$entries3$_i[0], value = _Object$entries3$_i[1];
conflictFreeKey = generateConflictFreeFilename(_key, existingFiles); // Always add metadata: true flag for globals files
if (typeof value === 'string') {
// For string URLs, we can't easily wrap them but need to track for later metadata addition
extraFilesToLoad[conflictFreeKey] = value;
globalsFileKeys.add(conflictFreeKey); // Track for loadExtraFiles
} else {
// For object values, add metadata directly
extraFilesToLoad[conflictFreeKey] = _objectSpread(_objectSpread({}, value), {}, {
metadata: true
});
}
existingFiles.add(conflictFreeKey); // Track the added file for subsequent iterations
}
}
// Add globals dependencies
allFilesUsed.push.apply(allFilesUsed, _toConsumableArray(globalsResult.dependencies));
// Add globals externals
allExternals = mergeExternals([allExternals, globalsResult.externals]);
}
} catch (err) {
_iterator5.e(err);
} finally {
_iterator5.f();
}
case 61:
if (!(Object.keys(extraFilesToLoad).length > 0)) {
_context6.next = 84;
break;
}
if (url) {
_context6.next = 78;
break;
}
// If there's no URL, we can only load extra files that have inline source or absolute URLs
loadableFiles = {};
for (_i8 = 0, _Object$entries4 = Object.entries(extraFilesToLoad); _i8 < _Object$entries4.length; _i8++) {
_Object$entries4$_i = _slicedToArray(_Object$entries4[_i8], 2), _key2 = _Object$entries4$_i[0], _value = _Object$entries4$_i[1];
if (typeof _value !== 'string' && _value.source !== undefined) {
// Inline source - can always load
loadableFiles[_key2] = _value;
} else if (typeof _value === 'string' && (_value.includes('://') || _value.startsWith('/'))) {
// Absolute URL - can load without base URL
loadableFiles[_key2] = _value;
} else {
console.warn("Skipping extra file \"".concat(_key2, "\" - no URL provided and file requires loading from external source"));
}
}
if (!(Object.keys(loadableFiles).length > 0)) {
_context6.next = 76;
break;
}
// Process loadable files: inline sources without URL-based loading, absolute URLs with loading
for (_i9 = 0, _Object$entries5 = Object.entries(loadableFiles); _i9 < _Object$entries5.length; _i9++) {
_Object$entries5$_i = _slicedToArray(_Object$entries5[_i9], 2), _key3 = _Object$entries5$_i[0], _value2 = _Object$entries5$_i[1];
if (typeof _value2 !== 'string') {
// Inline source - preserve metadata if it was marked as globals
metadata = _value2.metadata || globalsFileKeys.has(_key3) ? true : undefined;
allExtraFiles[normalizePathKey(_key3)] = _objectSpread({
source: _value2.source,
transforms: _value2.transforms
}, metadata !== undefined && {
metadata: metadata
});
}
}
// For absolute URLs, we need to load them
urlFilesToLoad = {};
for (_i0 = 0, _Object$entries6 = Object.entries(loadableFiles); _i0 < _Object$entries6.length; _i0++) {
_Object$entries6$_i = _slicedToArray(_Object$entries6[_i0], 2), _key4 = _Object$entries6$_i[0], _value3 = _Object$entries6$_i[1];
if (typeof _value3 === 'string') {
urlFilesToLoad[_key4] = _value3;
}
}
if (!(Object.keys(urlFilesToLoad).length > 0)) {
_context6.next = 76;
break;
}
_context6.next = 72;
return loadExtraFiles(variantName, urlFilesToLoad, '',
// No base URL needed for absolute URLs
'',
// No entry URL
loadSource, sourceParser, sourceTransformers, loadSourceCache, _objectSpread(_objectSpread({}, options), {}, {
loadedFiles: loadedFiles
}), variant.allFilesListed || false, knownExtraFiles, globalsFileKeys // Pass globals file tracking
);
case 72:
extraFilesResult = _context6.sent;
allExtraFiles = _objectSpread(_objectSpread({}, allExtraFiles), extraFilesResult.extraFiles);
allFilesUsed.push.apply(allFilesUsed, _toConsumableArray(extraFilesResult.allFilesUsed));
allExternals = mergeExternals([allExternals, extraFilesResult.allExternals]);
case 76:
_context6.next = 84;
break;
case 78:
_context6.next = 80;
return loadExtraFiles(variantName, extraFilesToLoad, url, url,
// Entry URL is the same as the main file URL
loadSource, sourceParser, sourceTransformers, loadSourceCache, _objectSpread(_objectSpread({}, options), {}, {
loadedFiles: loadedFiles
}), variant.allFilesListed || false, knownExtraFiles, globalsFileKeys // Pass globals file tracking
);
case 80:
_extraFilesResult = _context6.sent;
allExtraFiles = _extraFilesResult.extraFiles;
allFilesUsed.push.apply(allFilesUsed, _toConsumableArray(_extraFilesResult.allFilesUsed));
allExternals = mergeExternals([allExternals, _extraFilesResult.allExternals]);
case 84:
// Note: metadata marking is now handled during loadExtraFiles processing
finalVariant = _objectSpread(_objectSpread({}, variant), {}, {
source: mainFileResult.source,
transforms: mainFileResult.transforms,
extraFiles: Object.keys(allExtraFiles).length > 0 ? allExtraFiles : undefined,
externals: Object.keys(allExternals).length > 0 ? Object.keys(allExternals) : undefined
});
return _context6.abrupt("return", {
code: finalVariant,
dependencies: Array.from(new Set(allFilesUsed)),
// Remove duplicates
externals: allExternals
});
case 86:
case "end":
return _context6.stop();
}
}, _callee5, null, [[13, 19]]);
}));
return _loadVariant.apply(this, arguments);
}