@mui/internal-docs-infra 0.1.1-alpha.13 → 0.1.1-alpha.14

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.
@@ -1,5 +1,5 @@
1
- import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
2
1
  import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
2
+ import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
3
3
  /**
4
4
  * Export variant functionality to add extra files like package.json, tsconfig, etc.
5
5
  * Users can pass configuration options that vary the output here.
@@ -7,7 +7,37 @@ import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
7
7
 
8
8
  import { externalsToPackages } from "../pipeline/loaderUtils/index.js";
9
9
  import { getFileNameFromUrl } from "../pipeline/loaderUtils/getFileNameFromUrl.js";
10
- import { createPathContext } from "./examineVariant.js";
10
+ import { createPathContext } from "../CodeHighlighter/examineVariant.js";
11
+ import { mergeMetadata, extractMetadata } from "../CodeHighlighter/mergeMetadata.js";
12
+ /**
13
+ * Merges multiple file objects into a single object.
14
+ * Similar to mergeExternals but for file structures.
15
+ * Automatically adds metadata: false to files that don't have a metadata property.
16
+ */
17
+ function mergeFiles() {
18
+ var merged = {};
19
+ for (var _len = arguments.length, fileSets = new Array(_len), _key = 0; _key < _len; _key++) {
20
+ fileSets[_key] = arguments[_key];
21
+ }
22
+ for (var _i = 0, _fileSets = fileSets; _i < _fileSets.length; _i++) {
23
+ var fileSet = _fileSets[_i];
24
+ for (var _i2 = 0, _Object$entries = Object.entries(fileSet); _i2 < _Object$entries.length; _i2++) {
25
+ var _Object$entries$_i = _slicedToArray(_Object$entries[_i2], 2),
26
+ fileName = _Object$entries$_i[0],
27
+ fileData = _Object$entries$_i[1];
28
+ // Later files override earlier ones (similar to Object.assign behavior)
29
+ var normalizedData = typeof fileData === 'string' ? {
30
+ source: fileData
31
+ } : _objectSpread({}, fileData);
32
+ // Add metadata: false if not already set (source files default to false)
33
+ if (!('metadata' in normalizedData)) {
34
+ normalizedData.metadata = false;
35
+ }
36
+ merged[fileName] = normalizedData;
37
+ }
38
+ }
39
+ return merged;
40
+ }
11
41
 
12
42
  /**
13
43
  * Extract filename from URL or return undefined if not available
@@ -30,15 +60,15 @@ export function getFilenameFromVariant(variantCode) {
30
60
  export function generateEntrypointFilename(existingFiles, sourceFilename, useTypescript) {
31
61
  var pathPrefix = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';
32
62
  var ext = useTypescript ? 'tsx' : 'jsx';
33
- var candidates = ["".concat(pathPrefix, "index.").concat(ext), "".concat(pathPrefix, "entrypoint.").concat(ext), "".concat(pathPrefix, "main.").concat(ext)];
63
+ var candidates = ["".concat(pathPrefix, "App.").concat(ext), "".concat(pathPrefix, "entrypoint.").concat(ext), "".concat(pathPrefix, "main.").concat(ext)];
34
64
 
35
65
  // If we have a source filename, also try variations
36
66
  if (sourceFilename) {
37
67
  var baseName = sourceFilename.replace(/\.[^.]*$/, '');
38
68
  candidates.push("".concat(pathPrefix).concat(baseName, "-entry.").concat(ext));
39
69
  }
40
- for (var _i = 0, _candidates = candidates; _i < _candidates.length; _i++) {
41
- var candidate = _candidates[_i];
70
+ for (var _i3 = 0, _candidates = candidates; _i3 < _candidates.length; _i3++) {
71
+ var candidate = _candidates[_i3];
42
72
  if (candidate !== "".concat(pathPrefix).concat(sourceFilename) && !existingFiles[candidate]) {
43
73
  return candidate;
44
74
  }
@@ -74,17 +104,24 @@ export function defaultHtmlTemplate(_ref) {
74
104
  return "<!doctype html>\n<html lang=\"".concat(language, "\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>").concat(title, "</title>\n <meta name=\"description\" content=\"").concat(description, "\" />").concat(head ? "\n ".concat(head) : '', "\n </head>\n <body>\n <div id=\"root\"></div>").concat(entrypoint ? "\n <script type=\"module\" src=\"".concat(entrypoint, "\"></script>") : '', "\n </body>\n</html>");
75
105
  }
76
106
  /**
77
- * Export a VariantCode with additional configuration files
78
- * Returns an object with the exported VariantCode and rootPath path
107
+ * Export a variant as a standalone project with metadata files properly scoped
79
108
  */
80
109
  export function exportVariant(variantCode) {
110
+ var _frameworkFiles$varia;
81
111
  var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
82
112
  var _config$title = config.title,
83
113
  title = _config$title === void 0 ? 'Demo' : _config$title,
84
114
  _config$description = config.description,
85
115
  description = _config$description === void 0 ? 'Demo created with Vite' : _config$description,
116
+ variantName = config.variantName,
117
+ _config$language = config.language,
118
+ language = _config$language === void 0 ? 'en' : _config$language,
86
119
  _config$htmlPrefix = config.htmlPrefix,
87
120
  htmlPrefix = _config$htmlPrefix === void 0 ? '' : _config$htmlPrefix,
121
+ _config$sourcePrefix = config.sourcePrefix,
122
+ sourcePrefix = _config$sourcePrefix === void 0 ? 'src/' : _config$sourcePrefix,
123
+ _config$assetPrefix = config.assetPrefix,
124
+ assetPrefix = _config$assetPrefix === void 0 ? '' : _config$assetPrefix,
88
125
  _config$frameworkHand = config.frameworkHandlesEntrypoint,
89
126
  frameworkHandlesEntrypoint = _config$frameworkHand === void 0 ? false : _config$frameworkHand,
90
127
  htmlTemplate = config.htmlTemplate,
@@ -106,7 +143,23 @@ export function exportVariant(variantCode) {
106
143
  _config$extraMetadata = config.extraMetadataFiles,
107
144
  extraMetadataFiles = _config$extraMetadata === void 0 ? {} : _config$extraMetadata,
108
145
  _config$frameworkFile = config.frameworkFiles,
109
- frameworkFiles = _config$frameworkFile === void 0 ? {} : _config$frameworkFile;
146
+ frameworkFiles = _config$frameworkFile === void 0 ? {} : _config$frameworkFile,
147
+ transformVariant = config.transformVariant;
148
+
149
+ // Use extractMetadata to properly separate metadata and non-metadata files
150
+ var _extractMetadata = extractMetadata(variantCode),
151
+ processedVariantCode = _extractMetadata.variant,
152
+ processedGlobals = _extractMetadata.metadata;
153
+ if (transformVariant) {
154
+ var transformed = transformVariant(processedVariantCode, variantName, processedGlobals);
155
+ if (transformed) {
156
+ // Re-extract metadata after transformation
157
+ var result = extractMetadata(transformed.variant || variantCode);
158
+ processedVariantCode = result.variant;
159
+ // Combine metadata from extraction with transformed globals
160
+ processedGlobals = _objectSpread(_objectSpread({}, result.metadata), transformed.globals);
161
+ }
162
+ }
110
163
 
111
164
  // If packageType is explicitly provided (even as undefined), use that value
112
165
  var finalPackageType;
@@ -117,50 +170,70 @@ export function exportVariant(variantCode) {
117
170
  }
118
171
 
119
172
  // Get existing extraFiles and source filename
120
- var existingExtraFiles = variantCode.extraFiles || {};
121
- var sourceFilename = getFilenameFromVariant(variantCode);
173
+ var sourceFilename = getFilenameFromVariant(processedVariantCode);
122
174
 
123
- // Get path context to calculate proper URLs
124
- var pathContext = createPathContext(variantCode);
175
+ // Get path context to understand navigation
176
+ var pathContext = createPathContext(variantCode); // Determine if we need to rename the source file (if it's index.tsx in src dir)
125
177
 
126
- // Calculate the correct prefix for metadata files based on path depth
127
- var metadataPrefix = '../'.repeat(pathContext.maxBackNavigation + 1);
178
+ var ext = useTypescript ? 'tsx' : 'jsx';
179
+ var isSourceFileIndex = sourceFilename === "index.".concat(ext);
180
+ // Use urlDirectory to determine if it's in src root (should only have 'src' as the directory)
181
+ var isInSrcRoot = pathContext.urlDirectory.length <= 1;
182
+ var actualSourceFilename = sourceFilename;
183
+
184
+ // Use urlDirectory to construct the full path from src root
185
+ var directoryPath = pathContext.urlDirectory.slice(1).join('/'); // Remove 'src' and join the rest
186
+ var actualRootFile = directoryPath ? "".concat(sourcePrefix).concat(directoryPath, "/").concat(sourceFilename) : "".concat(sourcePrefix).concat(sourceFilename);
128
187
 
129
- // Generate unique entrypoint filename
130
- var entrypointFilename = generateEntrypointFilename(existingExtraFiles, sourceFilename, useTypescript);
188
+ // If the source file is index.tsx and it's in the src root, we need to rename it
189
+ if (isSourceFileIndex && isInSrcRoot) {
190
+ actualSourceFilename = generateEntrypointFilename(processedVariantCode.extraFiles || {}, sourceFilename, useTypescript);
191
+ actualRootFile = "".concat(sourcePrefix).concat(actualSourceFilename);
192
+ }
131
193
 
132
- // Calculate the entrypoint URL relative to the root
133
- var entrypoint = "/src/".concat(pathContext.pathInwardFromRoot).concat(entrypointFilename);
194
+ // The main entrypoint is always src/index.tsx (or .jsx)
195
+ var mainEntrypointFilename = "index.".concat(ext);
196
+ var entrypoint = "".concat(sourcePrefix).concat(mainEntrypointFilename);
134
197
 
135
198
  // Get relative import path for the main component
136
- var rootFile = "src/".concat(pathContext.pathInwardFromRoot).concat(sourceFilename);
137
- var importPath = getRelativeImportPath(sourceFilename);
138
- var importString = variantCode.namedExport ? "import { ".concat(variantCode.namedExport, " as App } from '").concat(importPath, "';") : "import App from '".concat(importPath, "';");
139
-
140
- // Create new extraFiles object
141
- var newExtraFiles = _objectSpread({}, existingExtraFiles);
142
-
143
- // Add framework-specific files (if any)
144
- for (var _i2 = 0, _Object$entries = Object.entries(frameworkFiles); _i2 < _Object$entries.length; _i2++) {
145
- var _fileData$metadata;
146
- var _Object$entries$_i = _slicedToArray(_Object$entries[_i2], 2),
147
- fileName = _Object$entries$_i[0],
148
- fileData = _Object$entries$_i[1];
149
- newExtraFiles[fileName] = {
150
- source: fileData.source,
151
- metadata: (_fileData$metadata = fileData.metadata) != null ? _fileData$metadata : true
152
- };
199
+ var importPath;
200
+ if (isInSrcRoot) {
201
+ // Component is in src root - import directly
202
+ importPath = getRelativeImportPath(actualSourceFilename);
203
+ } else {
204
+ // Component is in a subdirectory - import with full path from src root
205
+ // Use urlDirectory excluding the root level to get the full directory path
206
+ var _directoryPath = pathContext.urlDirectory.slice(1).join('/'); // Remove 'src' and join the rest
207
+ var componentPath = _directoryPath ? "".concat(_directoryPath, "/").concat(actualSourceFilename) : actualSourceFilename;
208
+ importPath = "./".concat((componentPath || '').replace(/\.[^.]*$/, '')); // Remove extension
209
+ }
210
+
211
+ // Strip /index from the end of import paths since module resolution handles it automatically
212
+ if (importPath.endsWith('/index')) {
213
+ importPath = importPath.slice(0, -6); // Remove '/index'
214
+ }
215
+ var importString = processedVariantCode.namedExport ? "import { ".concat(processedVariantCode.namedExport, " as App } from '").concat(importPath, "';") : "import App from '".concat(importPath, "';");
216
+
217
+ // Collect all files that will be generated
218
+ var generatedFiles = {};
219
+
220
+ // Update the variant's fileName if we renamed it
221
+ if (isSourceFileIndex && isInSrcRoot && actualSourceFilename && actualSourceFilename !== sourceFilename) {
222
+ processedVariantCode.fileName = actualSourceFilename;
153
223
  }
154
224
 
155
- // Check if we're using a framework (has framework files)
156
- var isFramework = frameworkFiles && Object.keys(frameworkFiles).length > 0;
157
- var externalPackages = externalsToPackages(variantCode.externals || []);
225
+ // Check if they're providing their own framework
226
+ var isFramework = 'frameworkFiles' in config;
227
+ var externalPackages = externalsToPackages(processedVariantCode.externals || []);
158
228
  var variantDeps = Object.keys(externalPackages).reduce(function (acc, pkg) {
159
229
  acc[pkg] = 'latest';
160
230
  return acc;
161
231
  }, {});
162
232
 
163
- // Generate package.json (always)
233
+ // Collect metadata files to be generated
234
+ var metadataFiles = {};
235
+
236
+ // Generate package.json
164
237
  var packageJson = _objectSpread(_objectSpread({
165
238
  "private": true,
166
239
  name: title.toLowerCase().replace(/[^a-z0-9]/g, '-'),
@@ -188,62 +261,35 @@ export function exportVariant(variantCode) {
188
261
  '@types/react-dom': 'latest'
189
262
  }), devDependencies)
190
263
  }, packageJsonFields);
191
- newExtraFiles["".concat(metadataPrefix, "package.json")] = {
192
- source: JSON.stringify(packageJson, null, 2),
193
- metadata: true
264
+ metadataFiles['package.json'] = {
265
+ source: JSON.stringify(packageJson, null, 2)
194
266
  };
195
267
 
196
268
  // Generate entrypoint and HTML files unless framework handles them
197
269
  if (!frameworkHandlesEntrypoint) {
198
- // Add index.html (with configurable prefix for different frameworks)
199
- var headContent = headTemplate ? headTemplate({
200
- sourcePrefix: '/src',
201
- assetPrefix: ''
202
- }) : undefined;
203
- var htmlContent = htmlTemplate ? htmlTemplate({
204
- language: 'en',
205
- title: title,
206
- description: description,
207
- head: headContent,
208
- entrypoint: entrypoint
209
- }) : defaultHtmlTemplate({
210
- language: 'en',
211
- title: title,
212
- description: description,
213
- head: headContent,
214
- entrypoint: entrypoint
215
- });
216
- var htmlFilePath = htmlPrefix ? "".concat(metadataPrefix).concat(htmlPrefix, "index.html") : "".concat(metadataPrefix, "index.html");
217
- newExtraFiles[htmlFilePath] = {
218
- source: htmlContent,
219
- metadata: true
220
- };
221
-
222
270
  // Create entrypoint file that imports the main component
223
271
  var defaultEntrypointContent = "import * as React from 'react';\nimport * as ReactDOM from 'react-dom/client';\n".concat(importString, "\n\nReactDOM.createRoot(document.getElementById('root')").concat(useTypescript ? '!' : '', ").render(\n <React.StrictMode>\n <App />\n </React.StrictMode>\n);");
224
272
  var entrypointContent = rootIndexTemplate ? rootIndexTemplate({
225
273
  importString: importString,
226
274
  useTypescript: useTypescript
227
275
  }) : defaultEntrypointContent;
228
- newExtraFiles[entrypointFilename] = {
229
- source: entrypointContent,
230
- metadata: false
276
+ generatedFiles[mainEntrypointFilename] = {
277
+ source: entrypointContent
231
278
  };
232
279
  }
233
280
 
234
281
  // Add Vite config file only if no framework files (Vite-specific)
235
282
  if (!isFramework) {
236
283
  var viteConfigContent = "import { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\nimport { externalsToPackages } from '../loaderUtils/externalsToPackages';\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [react()],\n define: { 'process.env': {} },\n});";
237
- newExtraFiles["".concat(metadataPrefix, "vite.config.").concat(useTypescript ? 'ts' : 'js')] = {
238
- source: viteConfigContent,
239
- metadata: true
284
+ metadataFiles["vite.config.".concat(useTypescript ? 'ts' : 'js')] = {
285
+ source: viteConfigContent
240
286
  };
241
287
  }
242
288
 
243
- // Add TypeScript configuration if requested (up one directory, metadata: true)
289
+ // Add TypeScript configuration if requested
244
290
  if (useTypescript) {
245
291
  // Check if frameworkFiles already includes a tsconfig
246
- var hasFrameworkTsConfig = frameworkFiles && Object.keys(frameworkFiles).some(function (fileName) {
292
+ var hasFrameworkTsConfig = (frameworkFiles == null ? void 0 : frameworkFiles.globals) && Object.keys(frameworkFiles.globals).some(function (fileName) {
247
293
  return fileName.includes('tsconfig.json') && !fileName.includes('tsconfig.node.json');
248
294
  });
249
295
  if (!hasFrameworkTsConfig) {
@@ -272,9 +318,8 @@ export function exportVariant(variantCode) {
272
318
  path: './tsconfig.node.json'
273
319
  }]
274
320
  });
275
- newExtraFiles["".concat(metadataPrefix, "tsconfig.json")] = {
276
- source: JSON.stringify(defaultTsConfig, null, 2),
277
- metadata: true
321
+ metadataFiles['tsconfig.json'] = {
322
+ source: JSON.stringify(defaultTsConfig, null, 2)
278
323
  };
279
324
  }
280
325
 
@@ -291,30 +336,61 @@ export function exportVariant(variantCode) {
291
336
  },
292
337
  include: ['vite.config.ts']
293
338
  };
294
- newExtraFiles["".concat(metadataPrefix, "tsconfig.node.json")] = {
295
- source: JSON.stringify(nodeTsConfig, null, 2),
296
- metadata: true
339
+ metadataFiles['tsconfig.node.json'] = {
340
+ source: JSON.stringify(nodeTsConfig, null, 2)
297
341
  };
298
342
  }
299
343
  }
300
344
 
301
- // Add custom metadata files (respect metadata flag)
302
- for (var _i3 = 0, _Object$entries2 = Object.entries(extraMetadataFiles); _i3 < _Object$entries2.length; _i3++) {
303
- var _fileData$metadata2;
304
- var _Object$entries2$_i = _slicedToArray(_Object$entries2[_i3], 2),
305
- _fileName = _Object$entries2$_i[0],
306
- _fileData = _Object$entries2$_i[1];
307
- newExtraFiles["".concat(metadataPrefix).concat(_fileName)] = {
308
- source: _fileData.source,
309
- metadata: (_fileData$metadata2 = _fileData.metadata) != null ? _fileData$metadata2 : true
345
+ // Generate HTML file after all files are ready
346
+ if (!frameworkHandlesEntrypoint) {
347
+ // Add index.html
348
+ var headContent = headTemplate ? headTemplate({
349
+ sourcePrefix: sourcePrefix,
350
+ assetPrefix: assetPrefix,
351
+ variant: processedVariantCode,
352
+ variantName: variantName
353
+ }) : undefined;
354
+ var htmlContent = htmlTemplate ? htmlTemplate({
355
+ language: language,
356
+ title: title,
357
+ description: description,
358
+ head: headContent,
359
+ entrypoint: entrypoint,
360
+ variant: processedVariantCode,
361
+ variantName: variantName
362
+ }) : defaultHtmlTemplate({
363
+ language: language,
364
+ title: title,
365
+ description: description,
366
+ head: headContent,
367
+ entrypoint: entrypoint
368
+ });
369
+ var htmlFileName = htmlPrefix ? "".concat(htmlPrefix, "index.html") : 'index.html';
370
+ metadataFiles[htmlFileName] = {
371
+ source: htmlContent
310
372
  };
311
373
  }
312
374
 
313
- // Return new VariantCode with updated extraFiles
375
+ // Merge all metadata files including framework metadata and globals
376
+ var allMetadataFiles = mergeFiles(processedGlobals || {}, metadataFiles, extraMetadataFiles, frameworkFiles.globals || {});
377
+
378
+ // Merge all files using mergeMetadata to properly position everything with 'src/' (sourcePrefix opt) prefix
379
+ var allSourceFilesWithFramework = mergeFiles(processedVariantCode.extraFiles || {}, generatedFiles, ((_frameworkFiles$varia = frameworkFiles.variant) == null ? void 0 : _frameworkFiles$varia.extraFiles) || {});
380
+
381
+ // Update the variant with all source files including framework source files
382
+ var finalVariantWithSources = _objectSpread(_objectSpread({}, processedVariantCode), {}, {
383
+ extraFiles: allSourceFilesWithFramework
384
+ });
385
+
386
+ // Use mergeMetadata to position everything correctly
387
+ var finalVariant = mergeMetadata(finalVariantWithSources, allMetadataFiles, {
388
+ metadataPrefix: sourcePrefix
389
+ });
390
+
391
+ // Return new VariantCode with properly positioned files
314
392
  return {
315
- exported: _objectSpread(_objectSpread({}, variantCode), {}, {
316
- extraFiles: newExtraFiles
317
- }),
318
- rootFile: rootFile
393
+ exported: finalVariant,
394
+ rootFile: actualRootFile
319
395
  };
320
396
  }
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * Flatten variant utility to convert a VariantCode into a flat files list
3
3
  * Handles relative path resolution and metadata file scoping
4
+ * Uses addPathsToVariant for the core logic, then flattens the result
4
5
  */
5
6
  import type { VariantCode } from "../CodeHighlighter/types.js";
6
7
  export interface FlatFile {
@@ -13,5 +14,6 @@ export interface FlattenedFiles {
13
14
  /**
14
15
  * Flatten a VariantCode into a flat files structure
15
16
  * Resolves relative paths and handles metadata file scoping
17
+ * Uses addPathsToVariant for path resolution logic
16
18
  */
17
19
  export declare function flattenVariant(variant: VariantCode): FlattenedFiles;
@@ -1 +1 @@
1
- {"version":3,"file":"flattenVariant.d.ts","sourceRoot":"","sources":["../../src/useDemo/flattenVariant.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAiB,MAAM,0BAA0B,CAAC;AAK3E,MAAM,WAAW,QAAQ;IACvB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED,MAAM,WAAW,cAAc;IAC7B,CAAC,QAAQ,EAAE,MAAM,GAAG,QAAQ,CAAC;CAC9B;AAiLD;;;GAGG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,WAAW,GAAG,cAAc,CA+BnE"}
1
+ {"version":3,"file":"flattenVariant.d.ts","sourceRoot":"","sources":["../../src/useDemo/flattenVariant.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAiB,MAAM,0BAA0B,CAAC;AAI3E,MAAM,WAAW,QAAQ;IACvB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED,MAAM,WAAW,cAAc;IAC7B,CAAC,QAAQ,EAAE,MAAM,GAAG,QAAQ,CAAC;CAC9B;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,WAAW,GAAG,cAAc,CA6BnE"}
@@ -1,204 +1,45 @@
1
1
  import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
2
2
  import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
3
- import _createForOfIteratorHelper from "@babel/runtime/helpers/esm/createForOfIteratorHelper";
4
3
  /**
5
4
  * Flatten variant utility to convert a VariantCode into a flat files list
6
5
  * Handles relative path resolution and metadata file scoping
6
+ * Uses addPathsToVariant for the core logic, then flattens the result
7
7
  */
8
8
 
9
9
  import { stringOrHastToString } from "../pipeline/hastUtils/index.js";
10
- import { getFileNameFromUrl } from "../pipeline/loaderUtils/getFileNameFromUrl.js";
11
- import { createPathContext } from "./examineVariant.js";
12
- /**
13
- * Resolve a relative path from a base URL to get the target directory structure
14
- */
15
- function resolveRelativePath(baseUrl, relativePath) {
16
- var url = new URL(baseUrl);
17
- var pathSegments = url.pathname.split('/').filter(Boolean);
18
- pathSegments.pop(); // Remove filename to get directory
19
-
20
- var relativeSegments = relativePath.split('/');
21
- var _iterator = _createForOfIteratorHelper(relativeSegments),
22
- _step;
23
- try {
24
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
25
- var segment = _step.value;
26
- if (segment === '..') {
27
- pathSegments.pop();
28
- } else if (segment !== '.' && segment !== '') {
29
- pathSegments.push(segment);
30
- }
31
- }
32
- } catch (err) {
33
- _iterator.e(err);
34
- } finally {
35
- _iterator.f();
36
- }
37
- return pathSegments.join('/');
38
- }
39
-
40
- /**
41
- * Process the main file and determine its final path
42
- */
43
- function processMainFile(variant, context) {
44
- var effectiveFileName = variant.fileName;
45
-
46
- // If fileName is missing but we have a URL, derive it from the URL
47
- if (!effectiveFileName && context.hasUrl) {
48
- var _getFileNameFromUrl = getFileNameFromUrl(context.actualUrl),
49
- fileName = _getFileNameFromUrl.fileName;
50
- effectiveFileName = fileName;
51
- }
52
- if (!effectiveFileName || variant.source === undefined) {
53
- return null;
54
- }
55
- var mainFilePath;
56
- if (context.hasUrl && context.maxBackNavigation > 0) {
57
- // URL with back navigation - calculate relative path from root level
58
- // TypeScript knows context.actualUrl is defined when context.hasUrl is true
59
- var urlObj = new URL(context.actualUrl);
60
- var fullPath = urlObj.pathname.substring(1); // Remove leading slash
61
- var relativePath = context.rootLevel ? fullPath.substring(context.rootLevel.length) : fullPath;
62
- mainFilePath = relativePath.replace(/\/[^/]+$/, "/".concat(effectiveFileName));
63
- } else if (context.hasUrl && variant.extraFiles && Object.keys(variant.extraFiles).length > 0) {
64
- // URL with extra files but no back navigation
65
- if (context.hasMetadata) {
66
- // For metadata cases, preserve the full directory structure
67
- mainFilePath = context.urlDirectory.length > 0 ? "".concat(context.urlDirectory.join('/'), "/").concat(effectiveFileName) : effectiveFileName;
68
- } else {
69
- // Check if all extra files are current directory references
70
- var allCurrentDir = Object.keys(variant.extraFiles).every(function (path) {
71
- return path.startsWith('./') || !path.startsWith('../') && !path.startsWith('.');
72
- });
73
- if (allCurrentDir) {
74
- // For current directory references without metadata, flatten to root
75
- mainFilePath = effectiveFileName;
76
- } else {
77
- // Use just the immediate parent directory
78
- var lastSegment = context.urlDirectory[context.urlDirectory.length - 1];
79
- mainFilePath = lastSegment ? "".concat(lastSegment, "/").concat(effectiveFileName) : effectiveFileName;
80
- }
81
- }
82
- } else {
83
- // Simple case - just use the filename
84
- mainFilePath = effectiveFileName;
85
- }
86
-
87
- // Add src/ prefix if we have metadata
88
- if (context.hasMetadata) {
89
- // When there are metadata files, simplify the main file path
90
- if (context.hasUrl && !context.maxBackNavigation) {
91
- // No back navigation - just use the filename
92
- mainFilePath = effectiveFileName;
93
- }
94
- mainFilePath = "src/".concat(mainFilePath);
95
- }
96
- return {
97
- path: mainFilePath,
98
- hasDirectory: mainFilePath.includes('/')
99
- };
100
- }
101
-
102
- /**
103
- * Process metadata files to determine their final paths
104
- */
105
- function processMetadataFile(relativePath) {
106
- // Extract everything after the back navigation, preserving directory structure
107
- return relativePath.replace(/^(\.\.\/)+/, '');
108
- }
109
-
110
- /**
111
- * Process extra file paths to determine their final paths
112
- */
113
- function processExtraFilePath(relativePath, context, mainFile) {
114
- if (relativePath.startsWith('./')) {
115
- // Current directory reference - just remove the ./
116
- return relativePath.substring(2);
117
- }
118
- if (relativePath.startsWith('../')) {
119
- // Back navigation - resolve relative to URL or create synthetic paths
120
- if (context.hasUrl) {
121
- // TypeScript knows context.actualUrl is defined when context.hasUrl is true
122
- var resolved = resolveRelativePath(context.actualUrl, relativePath);
123
- if (context.rootLevel) {
124
- var rootLevelClean = context.rootLevel.replace(/\/$/, '');
125
- if (resolved.startsWith("".concat(rootLevelClean, "/"))) {
126
- return resolved.substring(rootLevelClean.length + 1);
127
- }
128
- if (resolved === rootLevelClean) {
129
- return relativePath.split('/').pop() || relativePath;
130
- }
131
- return resolved;
132
- }
133
- return resolved;
134
- }
135
-
136
- // Fallback: if somehow we don't have a URL (shouldn't happen anymore with synthetic URLs)
137
- return relativePath.split('/').pop() || relativePath;
138
- }
139
-
140
- // Regular relative path (like 'dir/utils.ts')
141
- if (context.hasUrl && !context.hasMetadata && mainFile != null && mainFile.hasDirectory) {
142
- // Place relative to main file's directory if it has one
143
- var lastSegment = context.urlDirectory[context.urlDirectory.length - 1];
144
- return lastSegment ? "".concat(lastSegment, "/").concat(relativePath) : relativePath;
145
- }
146
- return relativePath;
147
- }
148
-
149
- /**
150
- * Process an extra file to determine its final path
151
- */
152
- function processExtraFile(relativePath, file, context, mainFile) {
153
- var finalPath;
154
- if (file.metadata) {
155
- finalPath = processMetadataFile(relativePath);
156
- } else {
157
- finalPath = processExtraFilePath(relativePath, context, mainFile);
158
-
159
- // Add src/ prefix if we have metadata (all paths are relative to main file)
160
- if (context.hasMetadata) {
161
- finalPath = "src/".concat(finalPath);
162
- }
163
- }
164
- return finalPath;
165
- }
166
-
10
+ import { addPathsToVariant } from "../CodeHighlighter/addPathsToVariant.js";
167
11
  /**
168
12
  * Flatten a VariantCode into a flat files structure
169
13
  * Resolves relative paths and handles metadata file scoping
14
+ * Uses addPathsToVariant for path resolution logic
170
15
  */
171
16
  export function flattenVariant(variant) {
172
17
  var result = {};
173
- var context = createPathContext(variant);
174
18
 
175
- // Process main file
176
- var mainFile = processMainFile(variant, context);
177
- if (mainFile && variant.source !== undefined) {
178
- result[mainFile.path] = {
179
- source: stringOrHastToString(variant.source)
19
+ // Use addPathsToVariant to get the structured paths
20
+ var variantWithPaths = addPathsToVariant(variant);
21
+
22
+ // Add main file if it exists
23
+ if (variantWithPaths.path && variantWithPaths.source !== undefined) {
24
+ result[variantWithPaths.path] = {
25
+ source: stringOrHastToString(variantWithPaths.source)
180
26
  };
181
27
  }
182
28
 
183
- // Process extra files
184
- if (variant.extraFiles) {
185
- for (var _i = 0, _Object$entries = Object.entries(variant.extraFiles); _i < _Object$entries.length; _i++) {
29
+ // Add extra files if they exist
30
+ if (variantWithPaths.extraFiles) {
31
+ for (var _i = 0, _Object$entries = Object.entries(variantWithPaths.extraFiles); _i < _Object$entries.length; _i++) {
186
32
  var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
187
33
  relativePath = _Object$entries$_i[0],
188
- fileContent = _Object$entries$_i[1];
189
- var file = typeof fileContent === 'string' ? {
190
- source: fileContent
191
- } : fileContent;
192
-
34
+ fileWithPath = _Object$entries$_i[1];
193
35
  // Skip files with no source content
194
- if (!file.source && file.source !== '') {
36
+ if (!fileWithPath.source && fileWithPath.source !== '') {
195
37
  continue;
196
38
  }
197
- var finalPath = processExtraFile(relativePath, file, context, mainFile);
198
- result[finalPath] = _objectSpread({
199
- source: stringOrHastToString(file.source || '')
200
- }, file.metadata && {
201
- metadata: file.metadata
39
+ result[fileWithPath.path] = _objectSpread({
40
+ source: stringOrHastToString(fileWithPath.source || '')
41
+ }, fileWithPath.metadata && {
42
+ metadata: fileWithPath.metadata
202
43
  });
203
44
  }
204
45
  }
@@ -1,6 +1,7 @@
1
1
  import * as React from 'react';
2
2
  import { UseCopierOpts } from "../useCopier/index.js";
3
3
  import type { ContentProps } from "../CodeHighlighter/types.js";
4
+ import { type ExportConfig } from "./exportVariant.js";
4
5
  /**
5
6
  * Demo templates use the exportVariant/exportVariantAsCra with flattenVariant pattern:
6
7
  *
@@ -23,6 +24,12 @@ type UseDemoOpts = {
23
24
  stackBlitzPrefix?: string;
24
25
  initialVariant?: string;
25
26
  initialTransform?: string;
27
+ /** Common export configuration applied to both StackBlitz and CodeSandbox */
28
+ export?: ExportConfig;
29
+ /** StackBlitz-specific export configuration (merged with common export config) */
30
+ exportStackBlitz?: ExportConfig;
31
+ /** CodeSandbox-specific export configuration (merged with common export config) */
32
+ exportCodeSandbox?: ExportConfig;
26
33
  };
27
34
  /**
28
35
  * Helper to create HTML form element with hidden inputs
@@ -1 +1 @@
1
- {"version":3,"file":"useDemo.d.ts","sourceRoot":"","sources":["../../src/useDemo/useDemo.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAI/B,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAQ7D;;;;;;;;;;;;;GAaG;AAEH,KAAK,WAAW,GAAG;IACjB,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,IAAI,CAAC,EAAE,aAAa,CAAC;IACrB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B,CAAC;AAEF;;GAEG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,eAAe,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAMvF;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,EAC3B,GAAG,EACH,QAAQ,EACR,MAAe,EACf,MAAiB,GAClB,EAAE;IACD,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,GAAG,IAAI,CAaP;AAGD,wBAAgB,OAAO,CAAC,CAAC,SAAS,EAAE,GAAG,EAAE,EAAE,YAAY,EAAE,YAAY,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,EAAE,WAAW;;;;;;;;;;;;;YAxD1E,CAAC;;;;;;;;;;;;;;;;;;;EA4KlB"}
1
+ {"version":3,"file":"useDemo.d.ts","sourceRoot":"","sources":["../../src/useDemo/useDemo.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAI/B,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAI7D,OAAO,EAAiB,KAAK,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAInE;;;;;;;;;;;;;GAaG;AAEH,KAAK,WAAW,GAAG;IACjB,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,IAAI,CAAC,EAAE,aAAa,CAAC;IACrB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,6EAA6E;IAC7E,MAAM,CAAC,EAAE,YAAY,CAAC;IACtB,kFAAkF;IAClF,gBAAgB,CAAC,EAAE,YAAY,CAAC;IAChC,mFAAmF;IACnF,iBAAiB,CAAC,EAAE,YAAY,CAAC;CAClC,CAAC;AAEF;;GAEG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,eAAe,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAMvF;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,EAC3B,GAAG,EACH,QAAQ,EACR,MAAe,EACf,MAAiB,GAClB,EAAE;IACD,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,GAAG,IAAI,CAaP;AAGD,wBAAgB,OAAO,CAAC,CAAC,SAAS,EAAE,GAAG,EAAE,EAAE,YAAY,EAAE,YAAY,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,EAAE,WAAW;;;;;;;;;;;;;YA9D3F,CAAD;;;;;;;;;;;;;;;;;;;EAqNC"}