react-cosmos 6.0.0-alpha.9 → 6.0.0-beta.1

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.
Files changed (158) hide show
  1. package/bin/cosmos-export.js +1 -3
  2. package/bin/cosmos-native.js +1 -3
  3. package/bin/cosmos.js +1 -7
  4. package/client.d.ts +1 -0
  5. package/client.js +1 -0
  6. package/config.schema.json +53 -15
  7. package/dist/cjsMocks/requireModule.js +7 -0
  8. package/dist/cjsMocks/resolve.js +7 -0
  9. package/dist/cjsMocks/staticPath.js +4 -0
  10. package/dist/client.d.ts +1 -0
  11. package/dist/client.js +1 -0
  12. package/dist/corePlugins/exposeImports.d.ts +2 -0
  13. package/dist/corePlugins/exposeImports.js +53 -0
  14. package/dist/corePlugins/httpProxy.d.ts +2 -0
  15. package/dist/corePlugins/httpProxy.js +21 -0
  16. package/dist/corePlugins/index.d.ts +2 -0
  17. package/dist/corePlugins/index.js +12 -0
  18. package/dist/corePlugins/openFile.d.ts +2 -0
  19. package/dist/corePlugins/openFile.js +59 -0
  20. package/dist/corePlugins/pluginEndpoint.d.ts +2 -0
  21. package/dist/corePlugins/pluginEndpoint.js +22 -0
  22. package/dist/corePlugins/portRetry.d.ts +2 -0
  23. package/dist/corePlugins/portRetry.js +14 -0
  24. package/dist/{server/cosmosConfig → cosmosConfig}/createCosmosConfig.js +37 -11
  25. package/dist/{server/cosmosConfig → cosmosConfig}/shared.js +2 -2
  26. package/dist/{server/cosmosConfig → cosmosConfig}/types.d.ts +12 -2
  27. package/dist/{server/cosmosPlugin → cosmosPlugin}/findCosmosPluginConfigs.js +2 -2
  28. package/dist/{server/cosmosPlugin → cosmosPlugin}/readCosmosPluginConfig.js +4 -7
  29. package/dist/{server/cosmosPlugin → cosmosPlugin}/types.d.ts +15 -3
  30. package/dist/devServer/expressApp.d.ts +5 -0
  31. package/dist/{server/devServer → devServer}/expressApp.js +2 -2
  32. package/dist/{server/devServer → devServer}/messageHandler.d.ts +1 -1
  33. package/dist/{server/devServer → devServer}/messageHandler.js +2 -2
  34. package/dist/devServer/startDevServer.d.ts +2 -0
  35. package/dist/{server/devServer → devServer}/startDevServer.js +23 -29
  36. package/dist/{server/export → export}/generateExport.js +21 -18
  37. package/dist/{server/getFixtures → getFixtures}/getFixtures.d.ts +6 -2
  38. package/dist/getFixtures/getFixtures.js +53 -0
  39. package/dist/getFixtures/importUserModules.d.ts +8 -0
  40. package/dist/getFixtures/importUserModules.js +28 -0
  41. package/dist/index.d.ts +20 -0
  42. package/dist/index.js +20 -1
  43. package/dist/jest.d.ts +4 -7
  44. package/dist/jest.js +4 -7
  45. package/dist/shared/applyServerConfigPlugins.d.ts +11 -0
  46. package/dist/shared/applyServerConfigPlugins.js +14 -0
  47. package/dist/shared/findNextAvailablePort.d.ts +1 -0
  48. package/dist/shared/findNextAvailablePort.js +29 -0
  49. package/dist/shared/getServerPlugins.d.ts +2 -0
  50. package/dist/shared/getServerPlugins.js +6 -0
  51. package/dist/shared/importServerPlugins.d.ts +3 -0
  52. package/dist/shared/importServerPlugins.js +16 -0
  53. package/dist/shared/playgroundHtml.d.ts +5 -0
  54. package/dist/{server/shared → shared}/playgroundHtml.js +25 -33
  55. package/dist/shared/staticPath.d.ts +1 -0
  56. package/dist/{server/shared → shared}/staticServer.js +3 -1
  57. package/dist/{server/testHelpers → testHelpers}/mockConsole.js +8 -4
  58. package/dist/{server/testHelpers → testHelpers}/mockFs.d.ts +2 -2
  59. package/dist/{server/testHelpers → testHelpers}/mockFs.js +26 -8
  60. package/dist/{server/testHelpers → testHelpers}/mockYargs.js +1 -0
  61. package/dist/{server/userDeps → userModules}/findUserModulePaths.js +2 -2
  62. package/dist/userModules/generateUserImports.d.ts +10 -0
  63. package/dist/{server/userDeps/generateUserDepsModule.js → userModules/generateUserImports.js} +8 -3
  64. package/dist/userModules/shared.d.ts +15 -0
  65. package/dist/{server/userDeps → userModules}/shared.js +16 -0
  66. package/dist/userModules/userImportsLazyTemplate.d.ts +2 -0
  67. package/dist/userModules/userImportsLazyTemplate.js +54 -0
  68. package/dist/userModules/userImportsTemplate.d.ts +2 -0
  69. package/dist/userModules/userImportsTemplate.js +56 -0
  70. package/dist/{server/utils → utils}/cli.d.ts +1 -0
  71. package/dist/utils/cli.js +4 -0
  72. package/dist/utils/fs.d.ts +5 -0
  73. package/dist/{server/utils → utils}/fs.js +10 -6
  74. package/dist/utils/json.d.ts +3 -0
  75. package/dist/utils/requireModule.d.ts +2 -0
  76. package/dist/utils/resolve.d.ts +2 -0
  77. package/package.json +10 -9
  78. package/dist/server/devServer/corePlugins/httpProxy.d.ts +0 -2
  79. package/dist/server/devServer/corePlugins/httpProxy.js +0 -18
  80. package/dist/server/devServer/corePlugins/openFile.d.ts +0 -2
  81. package/dist/server/devServer/corePlugins/openFile.js +0 -53
  82. package/dist/server/devServer/corePlugins/pluginEndpoint.d.ts +0 -2
  83. package/dist/server/devServer/corePlugins/pluginEndpoint.js +0 -17
  84. package/dist/server/devServer/corePlugins/userDepsFile.d.ts +0 -2
  85. package/dist/server/devServer/corePlugins/userDepsFile.js +0 -37
  86. package/dist/server/devServer/expressApp.d.ts +0 -5
  87. package/dist/server/devServer/startDevServer.d.ts +0 -2
  88. package/dist/server/getFixtures/getFixtures.js +0 -63
  89. package/dist/server/shared/playgroundHtml.d.ts +0 -6
  90. package/dist/server/shared/requirePluginModule.d.ts +0 -2
  91. package/dist/server/shared/requirePluginModule.js +0 -10
  92. package/dist/server/shared/resolveRendererUrl.d.ts +0 -1
  93. package/dist/server/shared/resolveRendererUrl.js +0 -7
  94. package/dist/server/testHelpers/mockEsmRequire.js +0 -13
  95. package/dist/server/testHelpers/mockEsmResolve.d.ts +0 -1
  96. package/dist/server/testHelpers/mockEsmResolve.js +0 -13
  97. package/dist/server/testHelpers/mockEsmStaticPath.d.ts +0 -1
  98. package/dist/server/testHelpers/mockEsmStaticPath.js +0 -7
  99. package/dist/server/userDeps/generateUserDepsModule.d.ts +0 -9
  100. package/dist/server/userDeps/getUserModules.d.ts +0 -8
  101. package/dist/server/userDeps/getUserModules.js +0 -26
  102. package/dist/server/userDeps/shared.d.ts +0 -5
  103. package/dist/server/userDeps/userDepsTemplate.d.ts +0 -11
  104. package/dist/server/userDeps/userDepsTemplate.js +0 -49
  105. package/dist/server/utils/cli.js +0 -4
  106. package/dist/server/utils/fs.d.ts +0 -4
  107. package/dist/server.d.ts +0 -20
  108. package/dist/server.js +0 -20
  109. package/server.d.ts +0 -1
  110. package/server.js +0 -1
  111. /package/dist/{server/utils → cjsMocks}/requireModule.d.ts +0 -0
  112. /package/dist/{server/utils → cjsMocks}/resolve.d.ts +0 -0
  113. /package/dist/{server/shared → cjsMocks}/staticPath.d.ts +0 -0
  114. /package/dist/{server/cosmosConfig → cosmosConfig}/createCosmosConfig.d.ts +0 -0
  115. /package/dist/{server/cosmosConfig → cosmosConfig}/detectCosmosConfig.d.ts +0 -0
  116. /package/dist/{server/cosmosConfig → cosmosConfig}/detectCosmosConfig.js +0 -0
  117. /package/dist/{server/cosmosConfig → cosmosConfig}/getCosmosConfigAtPath.d.ts +0 -0
  118. /package/dist/{server/cosmosConfig → cosmosConfig}/getCosmosConfigAtPath.js +0 -0
  119. /package/dist/{server/cosmosConfig → cosmosConfig}/shared.d.ts +0 -0
  120. /package/dist/{server/cosmosConfig → cosmosConfig}/types.js +0 -0
  121. /package/dist/{server/cosmosPlugin → cosmosPlugin}/findCosmosPluginConfigs.d.ts +0 -0
  122. /package/dist/{server/cosmosPlugin → cosmosPlugin}/pluginConfigs.d.ts +0 -0
  123. /package/dist/{server/cosmosPlugin → cosmosPlugin}/pluginConfigs.js +0 -0
  124. /package/dist/{server/cosmosPlugin → cosmosPlugin}/readCosmosPluginConfig.d.ts +0 -0
  125. /package/dist/{server/cosmosPlugin → cosmosPlugin}/types.js +0 -0
  126. /package/dist/{server/devServer → devServer}/httpServer.d.ts +0 -0
  127. /package/dist/{server/devServer → devServer}/httpServer.js +0 -0
  128. /package/dist/{server/export → export}/generateExport.d.ts +0 -0
  129. /package/dist/{server/shared → shared}/logPluginInfo.d.ts +0 -0
  130. /package/dist/{server/shared → shared}/logPluginInfo.js +0 -0
  131. /package/dist/{server/shared → shared}/playgroundUrl.d.ts +0 -0
  132. /package/dist/{server/shared → shared}/playgroundUrl.js +0 -0
  133. /package/dist/{server/shared → shared}/staticPath.js +0 -0
  134. /package/dist/{server/shared → shared}/staticServer.d.ts +0 -0
  135. /package/dist/{server/static → static}/favicon.ico +0 -0
  136. /package/dist/{server/static → static}/index.html +0 -0
  137. /package/dist/{server/testHelpers → testHelpers}/cwd.d.ts +0 -0
  138. /package/dist/{server/testHelpers → testHelpers}/cwd.js +0 -0
  139. /package/dist/{server/testHelpers → testHelpers}/mockConsole.d.ts +0 -0
  140. /package/dist/{server/testHelpers → testHelpers}/mockFetch.d.ts +0 -0
  141. /package/dist/{server/testHelpers → testHelpers}/mockFetch.js +0 -0
  142. /package/dist/{server/testHelpers → testHelpers}/mockYargs.d.ts +0 -0
  143. /package/dist/{server/userDeps → userModules}/findUserModulePaths.d.ts +0 -0
  144. /package/dist/{server/userDeps → userModules}/fixtureWatcher.d.ts +0 -0
  145. /package/dist/{server/userDeps → userModules}/fixtureWatcher.js +0 -0
  146. /package/dist/{server/utils → utils}/isNodeError.d.ts +0 -0
  147. /package/dist/{server/utils → utils}/isNodeError.js +0 -0
  148. /package/dist/{server/testHelpers/mockEsmRequire.d.ts → utils/json.js} +0 -0
  149. /package/dist/{server/utils → utils}/requireModule.js +0 -0
  150. /package/dist/{server/utils → utils}/requireSilent.d.ts +0 -0
  151. /package/dist/{server/utils → utils}/requireSilent.js +0 -0
  152. /package/dist/{server/utils → utils}/resolve.js +0 -0
  153. /package/dist/{server/utils → utils}/resolveLoose.d.ts +0 -0
  154. /package/dist/{server/utils → utils}/resolveLoose.js +0 -0
  155. /package/dist/{server/utils → utils}/resolveSilent.d.ts +0 -0
  156. /package/dist/{server/utils → utils}/resolveSilent.js +0 -0
  157. /package/dist/{server/utils → utils}/slash.d.ts +0 -0
  158. /package/dist/{server/utils → utils}/slash.js +0 -0
@@ -1,4 +1,4 @@
1
- import path from 'path';
1
+ import path from 'node:path';
2
2
  import { getCwdPath } from './cwd.js';
3
3
  jest.mock('../utils/fs', () => {
4
4
  const actual = jest.requireActual('../utils/fs');
@@ -8,8 +8,20 @@ jest.mock('../utils/fs', () => {
8
8
  async function importModule(moduleId) {
9
9
  if (!mocked)
10
10
  return actual.importModule(moduleId);
11
+ if (!fileMocks.hasOwnProperty(moduleId) &&
12
+ !fileMocks.hasOwnProperty(`${moduleId}.js`)) {
13
+ throw new Error(`Cannot find module '${moduleId}'`);
14
+ }
11
15
  return fileMocks[moduleId] || fileMocks[`${moduleId}.js`];
12
16
  }
17
+ async function importJson(filePath) {
18
+ if (!mocked)
19
+ return actual.importJson(filePath);
20
+ if (!fileMocks.hasOwnProperty(filePath)) {
21
+ throw new Error(`Cannot find JSON '${filePath}'`);
22
+ }
23
+ return fileMocks[filePath];
24
+ }
13
25
  function moduleExists(moduleId) {
14
26
  if (!mocked)
15
27
  return actual.moduleExists(moduleId);
@@ -28,6 +40,7 @@ jest.mock('../utils/fs', () => {
28
40
  }
29
41
  return {
30
42
  importModule,
43
+ importJson,
31
44
  moduleExists,
32
45
  fileExists,
33
46
  dirExists,
@@ -35,6 +48,10 @@ jest.mock('../utils/fs', () => {
35
48
  mocked = true;
36
49
  fileMocks = { ...fileMocks, [filePath]: fileMock };
37
50
  },
51
+ __mockJson(filePath, jsonMock) {
52
+ mocked = true;
53
+ fileMocks = { ...fileMocks, [filePath]: jsonMock };
54
+ },
38
55
  __mockDir(dirPath) {
39
56
  mocked = true;
40
57
  dirMocks = [...dirMocks, dirPath];
@@ -45,16 +62,17 @@ jest.mock('../utils/fs', () => {
45
62
  },
46
63
  };
47
64
  });
65
+ export function mockFile(filePath, fileMock) {
66
+ requireMocked().__mockFile(filePath, fileMock);
67
+ requireMocked().__mockDir(path.dirname(filePath));
68
+ }
48
69
  export function mockCosmosConfig(cosmosConfigPath, cosmosConfig) {
49
- mockFile(cosmosConfigPath, cosmosConfig);
70
+ const absPath = getCwdPath(cosmosConfigPath);
71
+ mockFile(absPath, cosmosConfig);
50
72
  }
51
- export function mockFile(filePath, fileContent) {
73
+ export function mockCwdModuleDefault(filePath, fileMock) {
52
74
  const absPath = getCwdPath(filePath);
53
- requireMocked().__mockFile(absPath, fileContent);
54
- requireMocked().__mockDir(path.dirname(absPath));
55
- }
56
- export function mockDir(dirPath) {
57
- requireMocked().__mockDir(getCwdPath(dirPath));
75
+ mockFile(absPath, { default: fileMock });
58
76
  }
59
77
  export function resetFsMock() {
60
78
  requireMocked().__resetMock();
@@ -3,6 +3,7 @@
3
3
  jest.mock('yargs/yargs', () => {
4
4
  let argv = {};
5
5
  const yargs = () => ({
6
+ boolean: () => yargs(),
6
7
  parseSync: () => argv,
7
8
  });
8
9
  yargs.__mockArgsv = (newArgv) => {
@@ -1,8 +1,8 @@
1
- import glob from 'glob';
1
+ import { globSync } from 'glob';
2
2
  import micromatch from 'micromatch';
3
3
  import { getDecoratorPatterns, getFixturePatterns } from './shared.js';
4
4
  export function findUserModulePaths({ rootDir, fixturesDir, fixtureFileSuffix, ignore, }) {
5
- const paths = glob.sync('**/*', {
5
+ const paths = globSync('**/*', {
6
6
  cwd: rootDir,
7
7
  absolute: true,
8
8
  ignore,
@@ -0,0 +1,10 @@
1
+ import { RendererConfig } from 'react-cosmos-core';
2
+ import { CosmosConfig } from '../cosmosConfig/types.js';
3
+ type Args<T extends RendererConfig> = {
4
+ cosmosConfig: CosmosConfig;
5
+ rendererConfig: T;
6
+ relativeToDir: string | null;
7
+ typeScript: boolean;
8
+ };
9
+ export declare function generateUserImports<T extends RendererConfig>({ cosmosConfig, rendererConfig, relativeToDir, typeScript, }: Args<T>): string;
10
+ export {};
@@ -1,6 +1,7 @@
1
1
  import { findUserModulePaths } from './findUserModulePaths.js';
2
- import { userDepsTemplate } from './userDepsTemplate.js';
3
- export function generateUserDepsModule({ cosmosConfig, rendererConfig, relativeToDir, }) {
2
+ import { userImportsLazyTemplate } from './userImportsLazyTemplate.js';
3
+ import { userImportsTemplate } from './userImportsTemplate.js';
4
+ export function generateUserImports({ cosmosConfig, rendererConfig, relativeToDir, typeScript, }) {
4
5
  const { rootDir, fixturesDir, fixtureFileSuffix, globalImports, ignore } = cosmosConfig;
5
6
  const { fixturePaths, decoratorPaths } = findUserModulePaths({
6
7
  rootDir,
@@ -8,12 +9,16 @@ export function generateUserDepsModule({ cosmosConfig, rendererConfig, relativeT
8
9
  fixtureFileSuffix,
9
10
  ignore,
10
11
  });
11
- return userDepsTemplate({
12
+ const template = cosmosConfig.lazy
13
+ ? userImportsLazyTemplate
14
+ : userImportsTemplate;
15
+ return template({
12
16
  globalImports,
13
17
  fixturePaths,
14
18
  decoratorPaths,
15
19
  rendererConfig,
16
20
  rootDir,
17
21
  relativeToDir,
22
+ typeScript,
18
23
  });
19
24
  }
@@ -0,0 +1,15 @@
1
+ import { RendererConfig } from 'react-cosmos-core';
2
+ export type UserImportsTemplateArgs = {
3
+ globalImports: string[];
4
+ fixturePaths: string[];
5
+ decoratorPaths: string[];
6
+ rendererConfig: RendererConfig;
7
+ rootDir: string;
8
+ relativeToDir: string | null;
9
+ typeScript: boolean;
10
+ };
11
+ export declare function getFixturePatterns(fixturesDir: string, fixtureFileSuffix: string): string[];
12
+ export declare function getDecoratorPatterns(): string[];
13
+ export declare function createImportMap(paths: string[], rootDir: string, relativeToDir: string | null): Record<string, string>;
14
+ export declare function importKeyPath(filePath: string, rootDir: string): string;
15
+ export declare function importPath(filePath: string, relativeToDir: string | null): string;
@@ -1,4 +1,6 @@
1
+ import path from 'path';
1
2
  import { replaceKeys } from 'react-cosmos-core';
3
+ import { slash } from '../utils/slash.js';
2
4
  // NODE: These can be made configurable if a proper need arises
3
5
  const FIXTURE_PATTERNS = [
4
6
  '**/<fixturesDir>/**/*.{js,jsx,ts,tsx}',
@@ -14,3 +16,17 @@ export function getFixturePatterns(fixturesDir, fixtureFileSuffix) {
14
16
  export function getDecoratorPatterns() {
15
17
  return DECORATOR_PATTERNS;
16
18
  }
19
+ export function createImportMap(paths, rootDir, relativeToDir) {
20
+ return paths.reduce((acc, p) => ({
21
+ ...acc,
22
+ [importKeyPath(p, rootDir)]: importPath(p, relativeToDir),
23
+ }), {});
24
+ }
25
+ export function importKeyPath(filePath, rootDir) {
26
+ return slash(path.relative(rootDir, filePath));
27
+ }
28
+ export function importPath(filePath, relativeToDir) {
29
+ return slash(relativeToDir
30
+ ? `.${path.sep}${path.relative(relativeToDir, filePath)}`
31
+ : filePath);
32
+ }
@@ -0,0 +1,2 @@
1
+ import { UserImportsTemplateArgs } from './shared.js';
2
+ export declare function userImportsLazyTemplate({ globalImports, fixturePaths, decoratorPaths, rendererConfig, rootDir, relativeToDir, typeScript, }: UserImportsTemplateArgs): string;
@@ -0,0 +1,54 @@
1
+ import { flatten } from 'lodash-es';
2
+ import { createImportMap, importPath, } from './shared.js';
3
+ export function userImportsLazyTemplate({ globalImports, fixturePaths, decoratorPaths, rendererConfig, rootDir, relativeToDir, typeScript, }) {
4
+ function ext(filePath) {
5
+ // Add compat with projects where allowImportingTsExtensions isn't enabled
6
+ return typeScript ? filePath.replace(/\.tsx?$/, '') : filePath;
7
+ }
8
+ function ts(annotation) {
9
+ return typeScript ? annotation : '';
10
+ }
11
+ const globalImportItems = globalImports.map(p => `import '${ext(importPath(p, relativeToDir))}';`);
12
+ const fixtures = createImportMap(fixturePaths, rootDir, relativeToDir);
13
+ const fixtureKeys = Object.keys(fixtures);
14
+ const fixtureItems = fixtureKeys.map(k => ` '${k}': { getModule: () => import('${ext(fixtures[k])}') }`);
15
+ const decorators = createImportMap(decoratorPaths, rootDir, relativeToDir);
16
+ const decoratorKeys = Object.keys(decorators);
17
+ const decoratorItems = decoratorKeys.map(k => ` '${k}': { getModule: () => import('${ext(decorators[k])}') }`);
18
+ const rendererConfigStr = JSON.stringify(rendererConfig, null, 2);
19
+ let importGroups = [globalImportItems];
20
+ if (typeScript) {
21
+ importGroups.unshift([
22
+ `import { RendererConfig, UserModuleWrappers } from 'react-cosmos-core';`,
23
+ ]);
24
+ }
25
+ return `
26
+ // This file is automatically generated by Cosmos. Add it to .gitignore and
27
+ // only edit if you know what you're doing.
28
+ ${importsStr(importGroups)}
29
+ export const rendererConfig${ts(': RendererConfig')} = ${rendererConfigStr};
30
+
31
+ const fixtures = {${objBody(fixtureItems)}};
32
+
33
+ const decorators = {${objBody(decoratorItems)}};
34
+
35
+ export const moduleWrappers${ts(': UserModuleWrappers')} = {
36
+ lazy: true,
37
+ fixtures,
38
+ decorators
39
+ };
40
+ `.trimStart();
41
+ }
42
+ function importsStr(items) {
43
+ if (flatten(items).length === 0) {
44
+ return '';
45
+ }
46
+ const str = items
47
+ .filter(rows => rows.length > 0)
48
+ .map(rows => rows.join('\n'))
49
+ .join('\n\n');
50
+ return `\n${str}\n`;
51
+ }
52
+ function objBody(items) {
53
+ return items.length > 0 ? `\n${items.join(`,\n`)}\n` : '';
54
+ }
@@ -0,0 +1,2 @@
1
+ import { UserImportsTemplateArgs } from './shared.js';
2
+ export declare function userImportsTemplate({ globalImports, fixturePaths, decoratorPaths, rendererConfig, rootDir, relativeToDir, typeScript, }: UserImportsTemplateArgs): string;
@@ -0,0 +1,56 @@
1
+ import { flatten } from 'lodash-es';
2
+ import { createImportMap, importPath, } from './shared.js';
3
+ export function userImportsTemplate({ globalImports, fixturePaths, decoratorPaths, rendererConfig, rootDir, relativeToDir, typeScript, }) {
4
+ function ext(filePath) {
5
+ // Add compat with projects where allowImportingTsExtensions isn't enabled
6
+ return typeScript ? filePath.replace(/\.tsx?$/, '') : filePath;
7
+ }
8
+ function ts(annotation) {
9
+ return typeScript ? annotation : '';
10
+ }
11
+ const globalImportItems = globalImports.map(p => `import '${ext(importPath(p, relativeToDir))}';`);
12
+ const fixtures = createImportMap(fixturePaths, rootDir, relativeToDir);
13
+ const fixtureKeys = Object.keys(fixtures);
14
+ const fixtureImports = fixtureKeys.map((k, i) => `import * as fixture${i} from '${ext(fixtures[k])}';`);
15
+ const fixtureItems = fixtureKeys.map((k, i) => ` '${k}': { module: fixture${i} }`);
16
+ const decorators = createImportMap(decoratorPaths, rootDir, relativeToDir);
17
+ const decoratorKeys = Object.keys(decorators);
18
+ const decoratorImports = decoratorKeys.map((k, i) => `import * as decorator${i} from '${ext(decorators[k])}';`);
19
+ const decoratorItems = decoratorKeys.map((k, i) => ` '${k}': { module: decorator${i} }`);
20
+ const rendererConfigStr = JSON.stringify(rendererConfig, null, 2);
21
+ let importGroups = [globalImportItems, fixtureImports, decoratorImports];
22
+ if (typeScript) {
23
+ importGroups.unshift([
24
+ `import { RendererConfig, UserModuleWrappers } from 'react-cosmos-core';`,
25
+ ]);
26
+ }
27
+ return `
28
+ // This file is automatically generated by Cosmos. Add it to .gitignore and
29
+ // only edit if you know what you're doing.
30
+ ${importsStr(importGroups)}
31
+ export const rendererConfig${ts(': RendererConfig')} = ${rendererConfigStr};
32
+
33
+ const fixtures = {${objBody(fixtureItems)}};
34
+
35
+ const decorators = {${objBody(decoratorItems)}};
36
+
37
+ export const moduleWrappers${ts(': UserModuleWrappers')} = {
38
+ lazy: false,
39
+ fixtures,
40
+ decorators
41
+ };
42
+ `.trimStart();
43
+ }
44
+ function importsStr(items) {
45
+ if (flatten(items).length === 0) {
46
+ return '';
47
+ }
48
+ const str = items
49
+ .filter(rows => rows.length > 0)
50
+ .map(rows => rows.join('\n'))
51
+ .join('\n\n');
52
+ return `\n${str}\n`;
53
+ }
54
+ function objBody(items) {
55
+ return items.length > 0 ? `\n${items.join(`,\n`)}\n` : '';
56
+ }
@@ -1,5 +1,6 @@
1
1
  export declare function getCliArgs(): {
2
2
  [x: string]: unknown;
3
+ lazy: boolean | undefined;
3
4
  _: (string | number)[];
4
5
  $0: string;
5
6
  };
@@ -0,0 +1,4 @@
1
+ import yargs from 'yargs/yargs';
2
+ export function getCliArgs() {
3
+ return yargs(process.argv.slice(2)).boolean('lazy').parseSync();
4
+ }
@@ -0,0 +1,5 @@
1
+ export declare function importModule<T>(filePath: string): Promise<T>;
2
+ export declare function importJson<T>(filePath: string): Promise<T>;
3
+ export declare function moduleExists(moduleId: string): boolean;
4
+ export declare function fileExists(filePath: string): boolean;
5
+ export declare function dirExists(dirPath: string): boolean;
@@ -1,16 +1,20 @@
1
1
  // NOTE: This API has been extracted to easily mock the file system in tests
2
- import fs from 'fs';
2
+ import fs from 'node:fs';
3
+ import url from 'node:url';
3
4
  import { requireModule } from './requireModule.js';
4
5
  import { resolve } from './resolve.js';
5
- export async function importModule(moduleId) {
6
- return moduleId.endsWith('.json')
7
- ? requireModule(moduleId)
8
- : import(moduleId);
6
+ export async function importModule(filePath) {
7
+ const fileUrl = url.pathToFileURL(filePath).href;
8
+ return import(fileUrl);
9
+ }
10
+ export async function importJson(filePath) {
11
+ return requireModule(filePath);
9
12
  }
10
13
  // Better than fs.exists because it works for module paths without an extension
11
14
  export function moduleExists(moduleId) {
12
15
  try {
13
- return resolve(moduleId) && true;
16
+ resolve(moduleId);
17
+ return true;
14
18
  }
15
19
  catch (err) {
16
20
  return false;
@@ -0,0 +1,3 @@
1
+ export type Json = string | number | boolean | null | {
2
+ [property: string]: Json;
3
+ } | Json[];
@@ -0,0 +1,2 @@
1
+ export declare function requireModule(moduleId: string): any;
2
+ export declare function requireFrom(fromDirectory: string, moduleId: string): any;
@@ -0,0 +1,2 @@
1
+ export declare function resolve(moduleId: string): string;
2
+ export declare function resolveFrom(fromDirectory: string, moduleId: string): string;
package/package.json CHANGED
@@ -1,31 +1,32 @@
1
1
  {
2
2
  "name": "react-cosmos",
3
- "version": "6.0.0-alpha.9",
3
+ "version": "6.0.0-beta.1",
4
4
  "description": "Sandbox for developing and testing UI components in isolation",
5
5
  "repository": "https://github.com/react-cosmos/react-cosmos/tree/main/packages/react-cosmos",
6
6
  "license": "MIT",
7
7
  "type": "module",
8
- "main": "index.js",
8
+ "main": "./index.js",
9
9
  "dependencies": {
10
10
  "@skidding/launch-editor": "^2.2.3",
11
11
  "chokidar": "^3.5.3",
12
12
  "express": "^4.18.2",
13
- "glob": "^8.1.0",
13
+ "glob": "^10.2.2",
14
14
  "http-proxy-middleware": "^2.0.6",
15
15
  "lodash-es": "^4.17.21",
16
16
  "micromatch": "^4.0.5",
17
17
  "open": "^8.4.2",
18
- "pem": "^1.14.6",
18
+ "pem": "^1.14.7",
19
19
  "pkg-up": "^4.0.0",
20
- "react-cosmos-core": "^6.0.0-alpha.9",
21
- "react-cosmos-ui": "^6.0.0-alpha.9",
22
- "ws": "^8.12.1",
23
- "yargs": "^17.7.1"
20
+ "react-cosmos-core": "6.0.0-beta.1",
21
+ "react-cosmos-renderer": "6.0.0-beta.1",
22
+ "react-cosmos-ui": "6.0.0-beta.1",
23
+ "ws": "^8.13.0",
24
+ "yargs": "^17.7.2"
24
25
  },
25
26
  "bin": {
26
27
  "cosmos": "./bin/cosmos.js",
27
28
  "cosmos-export": "./bin/cosmos-export.js",
28
29
  "cosmos-native": "./bin/cosmos-native.js"
29
30
  },
30
- "gitHead": "b155b223f904f5cc29e2f13ac79ab7c4b302ed2b"
31
+ "gitHead": "960ef665baa732f71ac8dd6cf19e4500d9cff8b8"
31
32
  }
@@ -1,2 +0,0 @@
1
- import { DevServerPluginArgs } from '../../cosmosPlugin/types.js';
2
- export declare function httpProxyDevServerPlugin({ platformType, cosmosConfig, expressApp, }: DevServerPluginArgs): void;
@@ -1,18 +0,0 @@
1
- import { createProxyMiddleware } from 'http-proxy-middleware';
2
- export function httpProxyDevServerPlugin({ platformType, cosmosConfig, expressApp, }) {
3
- if (platformType !== 'web')
4
- return;
5
- const httpProxyConfig = getHttpProxyCosmosConfig(cosmosConfig);
6
- Object.keys(httpProxyConfig).forEach(context => {
7
- const config = httpProxyConfig[context];
8
- if (typeof config === 'string') {
9
- expressApp.use(context, createProxyMiddleware(context, { target: config }));
10
- }
11
- else if (typeof config === 'object') {
12
- expressApp.use(context, createProxyMiddleware(context, config));
13
- }
14
- });
15
- }
16
- function getHttpProxyCosmosConfig(cosmosConfig) {
17
- return (cosmosConfig.httpProxy || {});
18
- }
@@ -1,2 +0,0 @@
1
- import { DevServerPluginArgs } from '../../cosmosPlugin/types.js';
2
- export default function openFileDevServerPlugin({ cosmosConfig, expressApp, }: DevServerPluginArgs): void;
@@ -1,53 +0,0 @@
1
- import launchEditor from '@skidding/launch-editor';
2
- import fs from 'fs';
3
- import open from 'open';
4
- import path from 'path';
5
- export default function openFileDevServerPlugin({ cosmosConfig, expressApp, }) {
6
- expressApp.get('/_open', (req, res) => {
7
- const { filePath, line, column } = getReqQuery(req);
8
- if (!filePath) {
9
- res.status(400).send(`File path missing`);
10
- return;
11
- }
12
- const absFilePath = resolveFilePath(cosmosConfig.rootDir, filePath);
13
- if (!fs.existsSync(absFilePath)) {
14
- res.status(404).send(`File not found at path: ${absFilePath}`);
15
- return;
16
- }
17
- new Promise((resolve, reject) => {
18
- const file = `${absFilePath}:${line}:${column}`;
19
- launchEditor(file, (fileName, errorMsg) => reject(errorMsg));
20
- // If launchEditor doesn't report error within 500ms we assume it worked
21
- setTimeout(resolve, 500);
22
- })
23
- // Fall back to open in case launchEditor fails. launchEditor only works
24
- // when the editor app is already open, but is favorable because it can
25
- // open a code file on a specific line & column.
26
- .catch(err => open(absFilePath))
27
- .catch(err => res.status(500).send('Failed to open file'))
28
- .then(() => res.send());
29
- });
30
- }
31
- function getReqQuery(req) {
32
- const { filePath, line, column } = req.query;
33
- if (typeof filePath !== 'string')
34
- throw new Error('filePath missing');
35
- return {
36
- filePath,
37
- line: typeof line === 'string' ? parseInt(line, 10) : 1,
38
- column: typeof column === 'string' ? parseInt(column, 10) : 1,
39
- };
40
- }
41
- function resolveFilePath(rootDir, filePath) {
42
- // This heuristic is needed because the open file endpoint is used for
43
- // multiple applications, which provide different file path types:
44
- // 1. Edit fixture button: Sends path relative to Cosmos rootDir
45
- // 2. react-error-overlay runtime error: Sends absolute path
46
- // 3. react-error-overlay compile error: Sends path relative to CWD
47
- if (path.isAbsolute(filePath)) {
48
- return filePath;
49
- }
50
- const cosmosRelPath = path.join(rootDir, filePath);
51
- const cwdRelPath = path.join(process.cwd(), filePath);
52
- return fs.existsSync(cosmosRelPath) ? cosmosRelPath : cwdRelPath;
53
- }
@@ -1,2 +0,0 @@
1
- import { DevServerPluginArgs } from '../../cosmosPlugin/types.js';
2
- export default function pluginEndpointDevServerPlugin({ cosmosConfig, expressApp, }: DevServerPluginArgs): void;
@@ -1,17 +0,0 @@
1
- import { resolveFromSilent, resolveSilent } from '../../utils/resolveSilent.js';
2
- export default function pluginEndpointDevServerPlugin({ cosmosConfig, expressApp, }) {
3
- expressApp.get('/_plugin/*.js', (req, res) => {
4
- const moduleId = req.params['0'];
5
- if (!moduleId) {
6
- res.sendStatus(404);
7
- return;
8
- }
9
- const resolvedPath = resolveSilent(`/${moduleId}`) ||
10
- resolveFromSilent(cosmosConfig.rootDir, moduleId);
11
- if (!resolvedPath) {
12
- res.sendStatus(404);
13
- return;
14
- }
15
- res.sendFile(resolvedPath);
16
- });
17
- }
@@ -1,2 +0,0 @@
1
- import { DevServerPluginArgs } from '../../cosmosPlugin/types.js';
2
- export declare function userDepsFileDevServerPlugin(args: DevServerPluginArgs): Promise<(() => void) | undefined>;
@@ -1,37 +0,0 @@
1
- import fs from 'fs/promises';
2
- import path from 'path';
3
- import { startFixtureWatcher } from '../../userDeps/fixtureWatcher.js';
4
- import { getPlaygroundUrl } from '../../shared/playgroundUrl.js';
5
- import { generateUserDepsModule } from '../../userDeps/generateUserDepsModule.js';
6
- import { getCliArgs } from '../../utils/cli.js';
7
- export async function userDepsFileDevServerPlugin(args) {
8
- if (!shouldGenerateUserDepsFile(args.platformType))
9
- return;
10
- const { cosmosConfig } = args;
11
- await generateUserDepsFile(cosmosConfig);
12
- const watcher = await startFixtureWatcher(cosmosConfig, 'all', () => {
13
- generateUserDepsFile(cosmosConfig);
14
- });
15
- return () => {
16
- watcher.close();
17
- };
18
- }
19
- function shouldGenerateUserDepsFile(platformType) {
20
- return (platformType === 'native' ||
21
- // CLI support for --external-userdeps flag (useful with react-native-web)
22
- Boolean(getCliArgs().externalUserdeps));
23
- }
24
- async function generateUserDepsFile(cosmosConfig) {
25
- const { userDepsFilePath } = cosmosConfig;
26
- const rendererConfig = {
27
- playgroundUrl: getPlaygroundUrl(cosmosConfig),
28
- };
29
- const userDepsModule = generateUserDepsModule({
30
- cosmosConfig,
31
- rendererConfig,
32
- relativeToDir: path.dirname(userDepsFilePath),
33
- });
34
- await fs.writeFile(userDepsFilePath, userDepsModule, 'utf8');
35
- const relUserDepsFilePath = path.relative(process.cwd(), userDepsFilePath);
36
- console.log(`[Cosmos] Generated ${relUserDepsFilePath}`);
37
- }
@@ -1,5 +0,0 @@
1
- import express from 'express';
2
- import { CosmosPluginConfig } from 'react-cosmos-core';
3
- import { CosmosConfig } from '../cosmosConfig/types.js';
4
- import { PlatformType } from '../cosmosPlugin/types.js';
5
- export declare function createExpressApp(platformType: PlatformType, cosmosConfig: CosmosConfig, pluginConfigs: CosmosPluginConfig[]): Promise<express.Express>;
@@ -1,2 +0,0 @@
1
- import { PlatformType } from '../cosmosPlugin/types.js';
2
- export declare function startDevServer(platformType: PlatformType): Promise<() => Promise<void>>;
@@ -1,63 +0,0 @@
1
- import path from 'path';
2
- import { createFixtureTree, flattenFixtureTree, getDecoratedFixtureElement, getFixtureListFromExports, getSortedDecoratorsForFixturePath, stringifyPlaygroundUrlQuery, stringifyRendererUrlQuery, } from 'react-cosmos-core';
3
- import { RENDERER_FILENAME } from '../shared/playgroundHtml.js';
4
- import { resolveRendererUrl } from '../shared/resolveRendererUrl.js';
5
- import { getUserModules } from '../userDeps/getUserModules.js';
6
- export function getFixtures(cosmosConfig) {
7
- const { fixturesDir, fixtureFileSuffix, rootDir } = cosmosConfig;
8
- const fixtureInfo = [];
9
- const { fixtures, decorators } = getUserModules(cosmosConfig);
10
- const fixtureList = getFixtureListFromExports(fixtures);
11
- const fixtureTree = createFixtureTree({
12
- fixtures: fixtureList,
13
- fixturesDir,
14
- fixtureFileSuffix,
15
- });
16
- const flatFixtureTree = flattenFixtureTree(fixtureTree);
17
- flatFixtureTree.forEach(({ fileName, fixtureId, name, parents }) => {
18
- const fixtureExport = fixtures[fixtureId.path];
19
- const fixture = fixtureId.name === undefined
20
- ? fixtureExport
21
- : fixtureExport[fixtureId.name];
22
- const treePath = [...parents, fileName];
23
- if (name)
24
- treePath.push(name);
25
- fixtureInfo.push({
26
- absoluteFilePath: path.join(rootDir, fixtureId.path),
27
- fileName,
28
- getElement: createFixtureElementGetter(fixture, fixtureId.path, decorators),
29
- name,
30
- parents,
31
- playgroundUrl: getPlaygroundUrl(cosmosConfig, fixtureId),
32
- relativeFilePath: fixtureId.path,
33
- rendererUrl: getRendererUrl(cosmosConfig, fixtureId),
34
- treePath,
35
- });
36
- });
37
- return fixtureInfo;
38
- }
39
- function getPlaygroundUrl(cosmosConfig, fixtureId) {
40
- const host = getPlaygroundHost(cosmosConfig);
41
- const query = stringifyPlaygroundUrlQuery({ fixtureId });
42
- return `${host}/?${query}`;
43
- }
44
- function getRendererUrl(cosmosConfig, fixtureId) {
45
- const { publicUrl, rendererUrl } = cosmosConfig;
46
- const query = stringifyRendererUrlQuery({ _fixtureId: fixtureId });
47
- if (rendererUrl)
48
- return `${rendererUrl}?${query}`;
49
- const host = getPlaygroundHost(cosmosConfig);
50
- const urlPath = resolveRendererUrl(publicUrl, RENDERER_FILENAME);
51
- return new URL(`${urlPath}?${query}`, host).toString();
52
- }
53
- function getPlaygroundHost({ hostname, port, https }) {
54
- return `${https ? 'https' : 'http'}://${hostname || 'localhost'}:${port}`;
55
- }
56
- function createFixtureElementGetter(fixture, fixturePath, decoratorsByPath) {
57
- const decorators = getSortedDecoratorsForFixturePath(fixturePath, decoratorsByPath);
58
- return () => getDecoratedFixtureElement(fixture, decorators, {
59
- fixtureState: {},
60
- setFixtureState: () => { },
61
- onErrorReset: () => { },
62
- });
63
- }
@@ -1,6 +0,0 @@
1
- import { CosmosPluginConfig } from 'react-cosmos-core';
2
- import { CosmosConfig } from '../cosmosConfig/types.js';
3
- import { PlatformType } from '../cosmosPlugin/types.js';
4
- export declare const RENDERER_FILENAME = "_renderer.html";
5
- export declare function getDevPlaygroundHtml(platformType: PlatformType, cosmosConfig: CosmosConfig, pluginConfigs: CosmosPluginConfig[]): Promise<string>;
6
- export declare function getExportPlaygroundHtml(cosmosConfig: CosmosConfig, pluginConfigs: CosmosPluginConfig[]): Promise<string>;
@@ -1,2 +0,0 @@
1
- import { CosmosPluginConfig } from 'react-cosmos-core';
2
- export declare function requirePluginModule<T>(rootDir: string, pluginConfig: CosmosPluginConfig, configKey: 'ui' | 'devServer' | 'export'): Promise<T>;
@@ -1,10 +0,0 @@
1
- import path from 'path';
2
- import { pathToFileURL } from 'url';
3
- export async function requirePluginModule(rootDir, pluginConfig, configKey) {
4
- const moduleId = pluginConfig[configKey];
5
- if (!moduleId) {
6
- throw new Error(`Module missing in plugin "${pluginConfig.name}": ${configKey}`);
7
- }
8
- const esModule = await import(pathToFileURL(path.resolve(rootDir, moduleId)).href);
9
- return esModule.default;
10
- }
@@ -1 +0,0 @@
1
- export declare function resolveRendererUrl(publicUrl: string, filename: string): string;