react-cosmos 6.0.0-alpha.0 → 6.0.0-alpha.11

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 (130) hide show
  1. package/bin/cosmos-export.js +1 -3
  2. package/bin/cosmos-native.js +1 -3
  3. package/bin/cosmos.js +1 -3
  4. package/config.schema.json +10 -0
  5. package/dist/corePlugins/httpProxy.d.ts +2 -0
  6. package/dist/corePlugins/httpProxy.js +21 -0
  7. package/dist/corePlugins/index.d.ts +2 -0
  8. package/dist/corePlugins/index.js +12 -0
  9. package/dist/corePlugins/openFile.d.ts +2 -0
  10. package/dist/corePlugins/openFile.js +56 -0
  11. package/dist/corePlugins/pluginEndpoint.d.ts +2 -0
  12. package/dist/corePlugins/pluginEndpoint.js +22 -0
  13. package/dist/corePlugins/portRetry.d.ts +2 -0
  14. package/dist/corePlugins/portRetry.js +11 -0
  15. package/dist/corePlugins/userDepsFile.d.ts +2 -0
  16. package/dist/{server/devServer/corePlugins → corePlugins}/userDepsFile.js +19 -16
  17. package/dist/{server/cosmosConfig → cosmosConfig}/createCosmosConfig.js +15 -0
  18. package/dist/{server/cosmosConfig → cosmosConfig}/shared.js +2 -2
  19. package/dist/{server/cosmosConfig → cosmosConfig}/types.d.ts +7 -0
  20. package/dist/{server/cosmosPlugin → cosmosPlugin}/pluginConfigs.js +1 -1
  21. package/dist/{server/cosmosPlugin → cosmosPlugin}/readCosmosPluginConfig.js +4 -7
  22. package/dist/{server/cosmosPlugin → cosmosPlugin}/types.d.ts +11 -0
  23. package/dist/{server/devServer → devServer}/messageHandler.d.ts +1 -1
  24. package/dist/{server/devServer → devServer}/messageHandler.js +2 -2
  25. package/dist/{server/devServer → devServer}/startDevServer.js +26 -24
  26. package/dist/{server/export → export}/generateExport.js +23 -12
  27. package/dist/{server/getFixtures → getFixtures}/getFixtures.js +3 -3
  28. package/dist/index.d.ts +21 -0
  29. package/dist/index.js +21 -1
  30. package/dist/jest.d.ts +7 -7
  31. package/dist/jest.js +7 -7
  32. package/dist/shared/findNextAvailablePort.d.ts +1 -0
  33. package/dist/shared/findNextAvailablePort.js +29 -0
  34. package/dist/shared/importServerPlugins.d.ts +3 -0
  35. package/dist/shared/importServerPlugins.js +16 -0
  36. package/dist/{server/shared → shared}/playgroundHtml.js +3 -3
  37. package/dist/shared/resolveRendererUrl.d.ts +1 -0
  38. package/dist/shared/resolveRendererUrl.js +7 -0
  39. package/dist/{server/testHelpers → testHelpers}/mockConsole.js +8 -4
  40. package/dist/{server/testHelpers → testHelpers}/mockFs.d.ts +2 -2
  41. package/dist/{server/testHelpers → testHelpers}/mockFs.js +26 -8
  42. package/dist/{server/userDeps → userDeps}/findUserModulePaths.d.ts +2 -1
  43. package/dist/{server/userDeps → userDeps}/findUserModulePaths.js +3 -3
  44. package/dist/{server/userDeps → userDeps}/fixtureWatcher.js +3 -3
  45. package/dist/{server/userDeps → userDeps}/generateUserDepsModule.js +2 -1
  46. package/dist/{server/userDeps → userDeps}/getUserModules.d.ts +1 -1
  47. package/dist/{server/userDeps → userDeps}/getUserModules.js +2 -1
  48. package/dist/{server/userDeps → userDeps}/shared.d.ts +0 -1
  49. package/dist/{server/userDeps → userDeps}/shared.js +0 -4
  50. package/dist/{server/utils → utils}/fs.d.ts +2 -1
  51. package/dist/{server/utils → utils}/fs.js +8 -5
  52. package/package.json +5 -5
  53. package/dist/server/devServer/corePlugins/httpProxy.d.ts +0 -2
  54. package/dist/server/devServer/corePlugins/httpProxy.js +0 -18
  55. package/dist/server/devServer/corePlugins/openFile.d.ts +0 -2
  56. package/dist/server/devServer/corePlugins/openFile.js +0 -53
  57. package/dist/server/devServer/corePlugins/pluginEndpoint.d.ts +0 -2
  58. package/dist/server/devServer/corePlugins/pluginEndpoint.js +0 -17
  59. package/dist/server/devServer/corePlugins/userDepsFile.d.ts +0 -2
  60. package/dist/server/shared/requirePluginModule.d.ts +0 -2
  61. package/dist/server/shared/requirePluginModule.js +0 -10
  62. package/dist/server/shared/resolveUrlPath.d.ts +0 -1
  63. package/dist/server/shared/resolveUrlPath.js +0 -12
  64. package/dist/server.d.ts +0 -20
  65. package/dist/server.js +0 -20
  66. package/server.d.ts +0 -1
  67. package/server.js +0 -1
  68. /package/dist/{server/cosmosConfig → cosmosConfig}/createCosmosConfig.d.ts +0 -0
  69. /package/dist/{server/cosmosConfig → cosmosConfig}/detectCosmosConfig.d.ts +0 -0
  70. /package/dist/{server/cosmosConfig → cosmosConfig}/detectCosmosConfig.js +0 -0
  71. /package/dist/{server/cosmosConfig → cosmosConfig}/getCosmosConfigAtPath.d.ts +0 -0
  72. /package/dist/{server/cosmosConfig → cosmosConfig}/getCosmosConfigAtPath.js +0 -0
  73. /package/dist/{server/cosmosConfig → cosmosConfig}/shared.d.ts +0 -0
  74. /package/dist/{server/cosmosConfig → cosmosConfig}/types.js +0 -0
  75. /package/dist/{server/cosmosPlugin → cosmosPlugin}/findCosmosPluginConfigs.d.ts +0 -0
  76. /package/dist/{server/cosmosPlugin → cosmosPlugin}/findCosmosPluginConfigs.js +0 -0
  77. /package/dist/{server/cosmosPlugin → cosmosPlugin}/pluginConfigs.d.ts +0 -0
  78. /package/dist/{server/cosmosPlugin → cosmosPlugin}/readCosmosPluginConfig.d.ts +0 -0
  79. /package/dist/{server/cosmosPlugin → cosmosPlugin}/types.js +0 -0
  80. /package/dist/{server/devServer → devServer}/expressApp.d.ts +0 -0
  81. /package/dist/{server/devServer → devServer}/expressApp.js +0 -0
  82. /package/dist/{server/devServer → devServer}/httpServer.d.ts +0 -0
  83. /package/dist/{server/devServer → devServer}/httpServer.js +0 -0
  84. /package/dist/{server/devServer → devServer}/startDevServer.d.ts +0 -0
  85. /package/dist/{server/export → export}/generateExport.d.ts +0 -0
  86. /package/dist/{server/getFixtures → getFixtures}/getFixtures.d.ts +0 -0
  87. /package/dist/{server/shared → shared}/logPluginInfo.d.ts +0 -0
  88. /package/dist/{server/shared → shared}/logPluginInfo.js +0 -0
  89. /package/dist/{server/shared → shared}/playgroundHtml.d.ts +0 -0
  90. /package/dist/{server/shared → shared}/playgroundUrl.d.ts +0 -0
  91. /package/dist/{server/shared → shared}/playgroundUrl.js +0 -0
  92. /package/dist/{server/shared → shared}/staticPath.d.ts +0 -0
  93. /package/dist/{server/shared → shared}/staticPath.js +0 -0
  94. /package/dist/{server/shared → shared}/staticServer.d.ts +0 -0
  95. /package/dist/{server/shared → shared}/staticServer.js +0 -0
  96. /package/dist/{server/static → static}/favicon.ico +0 -0
  97. /package/dist/{server/static → static}/index.html +0 -0
  98. /package/dist/{server/testHelpers → testHelpers}/cwd.d.ts +0 -0
  99. /package/dist/{server/testHelpers → testHelpers}/cwd.js +0 -0
  100. /package/dist/{server/testHelpers → testHelpers}/mockConsole.d.ts +0 -0
  101. /package/dist/{server/testHelpers → testHelpers}/mockEsmRequire.d.ts +0 -0
  102. /package/dist/{server/testHelpers → testHelpers}/mockEsmRequire.js +0 -0
  103. /package/dist/{server/testHelpers → testHelpers}/mockEsmResolve.d.ts +0 -0
  104. /package/dist/{server/testHelpers → testHelpers}/mockEsmResolve.js +0 -0
  105. /package/dist/{server/testHelpers → testHelpers}/mockEsmStaticPath.d.ts +0 -0
  106. /package/dist/{server/testHelpers → testHelpers}/mockEsmStaticPath.js +0 -0
  107. /package/dist/{server/testHelpers → testHelpers}/mockFetch.d.ts +0 -0
  108. /package/dist/{server/testHelpers → testHelpers}/mockFetch.js +0 -0
  109. /package/dist/{server/testHelpers → testHelpers}/mockYargs.d.ts +0 -0
  110. /package/dist/{server/testHelpers → testHelpers}/mockYargs.js +0 -0
  111. /package/dist/{server/userDeps → userDeps}/fixtureWatcher.d.ts +0 -0
  112. /package/dist/{server/userDeps → userDeps}/generateUserDepsModule.d.ts +0 -0
  113. /package/dist/{server/userDeps → userDeps}/userDepsTemplate.d.ts +0 -0
  114. /package/dist/{server/userDeps → userDeps}/userDepsTemplate.js +0 -0
  115. /package/dist/{server/utils → utils}/cli.d.ts +0 -0
  116. /package/dist/{server/utils → utils}/cli.js +0 -0
  117. /package/dist/{server/utils → utils}/isNodeError.d.ts +0 -0
  118. /package/dist/{server/utils → utils}/isNodeError.js +0 -0
  119. /package/dist/{server/utils → utils}/requireModule.d.ts +0 -0
  120. /package/dist/{server/utils → utils}/requireModule.js +0 -0
  121. /package/dist/{server/utils → utils}/requireSilent.d.ts +0 -0
  122. /package/dist/{server/utils → utils}/requireSilent.js +0 -0
  123. /package/dist/{server/utils → utils}/resolve.d.ts +0 -0
  124. /package/dist/{server/utils → utils}/resolve.js +0 -0
  125. /package/dist/{server/utils → utils}/resolveLoose.d.ts +0 -0
  126. /package/dist/{server/utils → utils}/resolveLoose.js +0 -0
  127. /package/dist/{server/utils → utils}/resolveSilent.d.ts +0 -0
  128. /package/dist/{server/utils → utils}/resolveSilent.js +0 -0
  129. /package/dist/{server/utils → utils}/slash.d.ts +0 -0
  130. /package/dist/{server/utils → utils}/slash.js +0 -0
@@ -3,9 +3,7 @@
3
3
  // Set the env before any code reads it
4
4
  process.env.NODE_ENV = process.env.NODE_ENV || 'production';
5
5
 
6
- const { generateExport } = await import(
7
- '../dist/server/export/generateExport.js'
8
- );
6
+ const { generateExport } = await import('../dist/export/generateExport.js');
9
7
 
10
8
  generateExport().catch(err => {
11
9
  console.log('[Cosmos] Export failed...');
@@ -3,9 +3,7 @@
3
3
  // Set the env before any code reads it
4
4
  process.env.NODE_ENV = process.env.NODE_ENV || 'development';
5
5
 
6
- const { startDevServer } = await import(
7
- '../dist/server/devServer/startDevServer.js'
8
- );
6
+ const { startDevServer } = await import('../dist/devServer/startDevServer.js');
9
7
 
10
8
  startDevServer('native').catch(err => {
11
9
  console.log('[Cosmos] Server crashed...');
package/bin/cosmos.js CHANGED
@@ -3,9 +3,7 @@
3
3
  // Set the env before any code reads it
4
4
  process.env.NODE_ENV = process.env.NODE_ENV || 'development';
5
5
 
6
- const { startDevServer } = await import(
7
- '../dist/server/devServer/startDevServer.js'
8
- );
6
+ const { startDevServer } = await import('../dist/devServer/startDevServer.js');
9
7
 
10
8
  // Auto disable Fast Refresh in CRA 4 until integration is implemented
11
9
  // https://github.com/react-cosmos/react-cosmos/issues/1272
@@ -50,6 +50,12 @@
50
50
  "type": "string",
51
51
  "minLength": 1
52
52
  },
53
+ "ignore": {
54
+ "description": "Patterns for ignoring fixture and decorator files (eg. [\"**/dist/**\"]]).",
55
+ "type": "array",
56
+ "items": { "type": "string", "minLength": 1 },
57
+ "uniqueItems": true
58
+ },
53
59
  "watchDirs": {
54
60
  "description": "Directories where the Cosmos server watches for fixture files changes while running. [default: [\".\"]]",
55
61
  "type": "array",
@@ -72,6 +78,10 @@
72
78
  "description": "Dev server port. [default: 5000]",
73
79
  "type": "number"
74
80
  },
81
+ "portRetries": {
82
+ "description": "Max number of port retries. [default: 10]",
83
+ "type": "number"
84
+ },
75
85
  "https": {
76
86
  "description": "Server will be served over HTTPS",
77
87
  "type": "boolean"
@@ -0,0 +1,2 @@
1
+ import { CosmosServerPlugin } from '../cosmosPlugin/types.js';
2
+ export declare const httpProxyServerPlugin: CosmosServerPlugin;
@@ -0,0 +1,21 @@
1
+ import { createProxyMiddleware } from 'http-proxy-middleware';
2
+ export const httpProxyServerPlugin = {
3
+ name: 'httpProxy',
4
+ devServer({ platformType, cosmosConfig, expressApp }) {
5
+ if (platformType !== 'web')
6
+ return;
7
+ const httpProxyConfig = getHttpProxyCosmosConfig(cosmosConfig);
8
+ Object.keys(httpProxyConfig).forEach(context => {
9
+ const config = httpProxyConfig[context];
10
+ if (typeof config === 'string') {
11
+ expressApp.use(context, createProxyMiddleware(context, { target: config }));
12
+ }
13
+ else if (typeof config === 'object') {
14
+ expressApp.use(context, createProxyMiddleware(context, config));
15
+ }
16
+ });
17
+ },
18
+ };
19
+ function getHttpProxyCosmosConfig(cosmosConfig) {
20
+ return (cosmosConfig.httpProxy || {});
21
+ }
@@ -0,0 +1,2 @@
1
+ import { CosmosServerPlugin } from '../cosmosPlugin/types.js';
2
+ export declare const coreServerPlugins: CosmosServerPlugin[];
@@ -0,0 +1,12 @@
1
+ import { httpProxyServerPlugin } from './httpProxy.js';
2
+ import { openFileServerPlugin } from './openFile.js';
3
+ import { pluginEndpointServerPlugin } from './pluginEndpoint.js';
4
+ import { portRetryServerPlugin } from './portRetry.js';
5
+ import { userDepsFileServerPlugin } from './userDepsFile.js';
6
+ export const coreServerPlugins = [
7
+ portRetryServerPlugin,
8
+ userDepsFileServerPlugin,
9
+ httpProxyServerPlugin,
10
+ openFileServerPlugin,
11
+ pluginEndpointServerPlugin,
12
+ ];
@@ -0,0 +1,2 @@
1
+ import { CosmosServerPlugin } from '../cosmosPlugin/types.js';
2
+ export declare const openFileServerPlugin: CosmosServerPlugin;
@@ -0,0 +1,56 @@
1
+ import launchEditor from '@skidding/launch-editor';
2
+ import fs from 'fs';
3
+ import open from 'open';
4
+ import path from 'path';
5
+ export const openFileServerPlugin = {
6
+ name: 'openFile',
7
+ devServer({ cosmosConfig, expressApp }) {
8
+ expressApp.get('/_open', (req, res) => {
9
+ const { filePath, line, column } = getReqQuery(req);
10
+ if (!filePath) {
11
+ res.status(400).send(`File path missing`);
12
+ return;
13
+ }
14
+ const absFilePath = resolveFilePath(cosmosConfig.rootDir, filePath);
15
+ if (!fs.existsSync(absFilePath)) {
16
+ res.status(404).send(`File not found at path: ${absFilePath}`);
17
+ return;
18
+ }
19
+ new Promise((resolve, reject) => {
20
+ const file = `${absFilePath}:${line}:${column}`;
21
+ launchEditor(file, (fileName, errorMsg) => reject(errorMsg));
22
+ // If launchEditor doesn't report error within 500ms we assume it worked
23
+ setTimeout(resolve, 500);
24
+ })
25
+ // Fall back to open in case launchEditor fails. launchEditor only works
26
+ // when the editor app is already open, but is favorable because it can
27
+ // open a code file on a specific line & column.
28
+ .catch(err => open(absFilePath))
29
+ .catch(err => res.status(500).send('Failed to open file'))
30
+ .then(() => res.send());
31
+ });
32
+ },
33
+ };
34
+ function getReqQuery(req) {
35
+ const { filePath, line, column } = req.query;
36
+ if (typeof filePath !== 'string')
37
+ throw new Error('filePath missing');
38
+ return {
39
+ filePath,
40
+ line: typeof line === 'string' ? parseInt(line, 10) : 1,
41
+ column: typeof column === 'string' ? parseInt(column, 10) : 1,
42
+ };
43
+ }
44
+ function resolveFilePath(rootDir, filePath) {
45
+ // This heuristic is needed because the open file endpoint is used for
46
+ // multiple applications, which provide different file path types:
47
+ // 1. Edit fixture button: Sends path relative to Cosmos rootDir
48
+ // 2. react-error-overlay runtime error: Sends absolute path
49
+ // 3. react-error-overlay compile error: Sends path relative to CWD
50
+ if (path.isAbsolute(filePath)) {
51
+ return filePath;
52
+ }
53
+ const cosmosRelPath = path.join(rootDir, filePath);
54
+ const cwdRelPath = path.join(process.cwd(), filePath);
55
+ return fs.existsSync(cosmosRelPath) ? cosmosRelPath : cwdRelPath;
56
+ }
@@ -0,0 +1,2 @@
1
+ import { CosmosServerPlugin } from '../cosmosPlugin/types.js';
2
+ export declare const pluginEndpointServerPlugin: CosmosServerPlugin;
@@ -0,0 +1,22 @@
1
+ import path from 'node:path';
2
+ import { resolveSilent } from '../utils/resolveSilent.js';
3
+ export const pluginEndpointServerPlugin = {
4
+ name: 'pluginEndpoint',
5
+ devServer({ cosmosConfig, expressApp }) {
6
+ expressApp.get('/_plugin/*.js', (req, res) => {
7
+ const modulePath = req.params['0'];
8
+ if (!modulePath) {
9
+ res.sendStatus(404);
10
+ return;
11
+ }
12
+ // The module path is always absolute, but Windows paths don't start
13
+ // with a slash (e.g. C:\foo\bar.js)
14
+ const resolvedPath = resolveSilent(path.isAbsolute(modulePath) ? modulePath : `/${modulePath}`);
15
+ if (!resolvedPath) {
16
+ res.sendStatus(404);
17
+ return;
18
+ }
19
+ res.sendFile(resolvedPath);
20
+ });
21
+ },
22
+ };
@@ -0,0 +1,2 @@
1
+ import { CosmosServerPlugin } from '../cosmosPlugin/types.js';
2
+ export declare const portRetryServerPlugin: CosmosServerPlugin;
@@ -0,0 +1,11 @@
1
+ import { findNextAvailablePort } from '../shared/findNextAvailablePort.js';
2
+ export const portRetryServerPlugin = {
3
+ name: 'portRetry',
4
+ async config({ cosmosConfig }) {
5
+ const { port, portRetries } = cosmosConfig;
6
+ return {
7
+ ...cosmosConfig,
8
+ port: portRetries ? await findNextAvailablePort(port, portRetries) : port,
9
+ };
10
+ },
11
+ };
@@ -0,0 +1,2 @@
1
+ import { CosmosServerPlugin } from '../cosmosPlugin/types.js';
2
+ export declare const userDepsFileServerPlugin: CosmosServerPlugin;
@@ -1,21 +1,24 @@
1
1
  import fs from 'fs/promises';
2
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
- }
3
+ import { getPlaygroundUrl } from '../shared/playgroundUrl.js';
4
+ import { startFixtureWatcher } from '../userDeps/fixtureWatcher.js';
5
+ import { generateUserDepsModule } from '../userDeps/generateUserDepsModule.js';
6
+ import { getCliArgs } from '../utils/cli.js';
7
+ export const userDepsFileServerPlugin = {
8
+ name: 'userDepsFile',
9
+ async devServer(args) {
10
+ if (!shouldGenerateUserDepsFile(args.platformType))
11
+ return;
12
+ const { cosmosConfig } = args;
13
+ await generateUserDepsFile(cosmosConfig);
14
+ const watcher = await startFixtureWatcher(cosmosConfig, 'all', () => {
15
+ generateUserDepsFile(cosmosConfig);
16
+ });
17
+ return () => {
18
+ watcher.close();
19
+ };
20
+ },
21
+ };
19
22
  function shouldGenerateUserDepsFile(platformType) {
20
23
  return (platformType === 'native' ||
21
24
  // CLI support for --external-userdeps flag (useful with react-native-web)
@@ -14,13 +14,16 @@ export function createCosmosConfig(rootDir, cosmosConfigInput = {}) {
14
14
  hostname: getHostname(cosmosConfigInput),
15
15
  https: getHttps(cosmosConfigInput),
16
16
  httpsOptions: getHttpsOptions(cosmosConfigInput, rootDir),
17
+ ignore: getIgnore(cosmosConfigInput),
17
18
  port: getPort(cosmosConfigInput),
19
+ portRetries: getPortRetries(cosmosConfigInput),
18
20
  plugins: getPlugins(cosmosConfigInput, rootDir),
19
21
  publicUrl: getPublicUrl(cosmosConfigInput),
20
22
  staticPath: getStaticPath(cosmosConfigInput, rootDir),
21
23
  userDepsFilePath: getUserDepsFilePath(cosmosConfigInput, rootDir),
22
24
  watchDirs: getWatchDirs(cosmosConfigInput, rootDir),
23
25
  rendererUrl: cosmosConfigInput.rendererUrl ?? null,
26
+ dom: getDomConfig(cosmosConfigInput.dom || {}),
24
27
  ui: cosmosConfigInput.ui || {},
25
28
  };
26
29
  }
@@ -46,6 +49,9 @@ function getHttpsOptions(cosmosConfigInput, rootDir) {
46
49
  }
47
50
  return null;
48
51
  }
52
+ function getIgnore({ ignore = [] }) {
53
+ return ['**/node_modules/**', ...ignore];
54
+ }
49
55
  function getPublicUrl({ publicUrl = '/' }) {
50
56
  return publicUrl;
51
57
  }
@@ -74,6 +80,9 @@ function getPort(cosmosConfigInput) {
74
80
  const { port = 5000 } = cosmosConfigInput;
75
81
  return port;
76
82
  }
83
+ function getPortRetries({ portRetries = 10 }) {
84
+ return portRetries;
85
+ }
77
86
  function getGlobalImports(cosmosConfigInput, rootDir) {
78
87
  const { globalImports = [] } = cosmosConfigInput;
79
88
  return globalImports.map(globalImport => resolveLoose(rootDir, globalImport));
@@ -82,3 +91,9 @@ function getPlugins(cosmosConfigInput, rootDir) {
82
91
  const { plugins = [] } = cosmosConfigInput;
83
92
  return plugins.map(plugin => resolveLoose(rootDir, plugin));
84
93
  }
94
+ function getDomConfig(cosmosConfigInput) {
95
+ const { containerQuerySelector = null } = cosmosConfigInput;
96
+ return {
97
+ containerQuerySelector,
98
+ };
99
+ }
@@ -1,7 +1,7 @@
1
- import { importModule } from '../utils/fs.js';
1
+ import { importJson } from '../utils/fs.js';
2
2
  export function getCurrentDir() {
3
3
  return process.cwd();
4
4
  }
5
5
  export async function importConfigFile(cosmosConfigPath) {
6
- return importModule(cosmosConfigPath);
6
+ return importJson(cosmosConfigPath);
7
7
  }
@@ -2,17 +2,23 @@ interface HttpsOptions {
2
2
  keyPath: string;
3
3
  certPath: string;
4
4
  }
5
+ export type CosmosDomConfig = {
6
+ containerQuerySelector: null | string;
7
+ };
5
8
  export type CosmosConfig = {
6
9
  exportPath: string;
7
10
  detectLocalPlugins: boolean;
8
11
  disablePlugins: boolean;
12
+ dom: CosmosDomConfig;
9
13
  fixtureFileSuffix: string;
10
14
  fixturesDir: string;
11
15
  globalImports: string[];
12
16
  hostname: null | string;
13
17
  https: boolean;
14
18
  httpsOptions: null | HttpsOptions;
19
+ ignore: string[];
15
20
  port: number;
21
+ portRetries: number;
16
22
  plugins: string[];
17
23
  publicUrl: string;
18
24
  rendererUrl: string | null;
@@ -25,5 +31,6 @@ export type CosmosConfig = {
25
31
  [pluginName: string]: {};
26
32
  };
27
33
  };
34
+ export type CosmosDomConfigInput = Partial<CosmosDomConfig>;
28
35
  export type CosmosConfigInput = Partial<CosmosConfig>;
29
36
  export {};
@@ -9,7 +9,7 @@ export async function getPluginConfigs({ cosmosConfig, relativePaths, }) {
9
9
  return moduleConfigs;
10
10
  const localConfigs = await findCosmosPluginConfigs({
11
11
  rootDir,
12
- ignore: [`${exportPath}/**`],
12
+ ignore: ['**/node_modules/**', `${exportPath}/**`],
13
13
  relativePaths,
14
14
  });
15
15
  return [...moduleConfigs, ...localConfigs];
@@ -1,8 +1,8 @@
1
1
  import path from 'path';
2
- import { importModule } from '../utils/fs.js';
2
+ import { importJson } from '../utils/fs.js';
3
3
  import { resolveSilent } from '../utils/resolveSilent.js';
4
4
  export async function readCosmosPluginConfig({ rootDir, configPath, relativePaths, }) {
5
- const rawConfig = await importModule(configPath);
5
+ const rawConfig = await importJson(configPath);
6
6
  const pluginRootDir = path.dirname(configPath);
7
7
  const config = {
8
8
  name: rawConfig.name,
@@ -13,11 +13,8 @@ export async function readCosmosPluginConfig({ rootDir, configPath, relativePath
13
13
  if (rawConfig.ui) {
14
14
  config.ui = resolvePluginPath(config.name, rootDir, pluginRootDir, rawConfig.ui, relativePaths);
15
15
  }
16
- if (rawConfig.devServer) {
17
- config.devServer = resolvePluginPath(config.name, rootDir, pluginRootDir, rawConfig.devServer, relativePaths);
18
- }
19
- if (rawConfig.export) {
20
- config.export = resolvePluginPath(config.name, rootDir, pluginRootDir, rawConfig.export, relativePaths);
16
+ if (rawConfig.server) {
17
+ config.server = resolvePluginPath(config.name, rootDir, pluginRootDir, rawConfig.server, relativePaths);
21
18
  }
22
19
  return config;
23
20
  }
@@ -4,6 +4,11 @@ import http from 'http';
4
4
  import { MessageType } from 'react-cosmos-core';
5
5
  import { CosmosConfig } from '../cosmosConfig/types.js';
6
6
  export type PlatformType = 'web' | 'native';
7
+ export type CosmosConfigPluginArgs = {
8
+ cosmosConfig: CosmosConfig;
9
+ platformType: PlatformType;
10
+ };
11
+ export type CosmosConfigPlugin = (args: CosmosConfigPluginArgs) => Promise<CosmosConfig> | CosmosConfig;
7
12
  export type DevServerPluginArgs = {
8
13
  cosmosConfig: CosmosConfig;
9
14
  platformType: PlatformType;
@@ -19,3 +24,9 @@ export type ExportPluginArgs = {
19
24
  cosmosConfig: CosmosConfig;
20
25
  };
21
26
  export type ExportPlugin = (args: ExportPluginArgs) => unknown;
27
+ export type CosmosServerPlugin = {
28
+ name: string;
29
+ config?: CosmosConfigPlugin;
30
+ devServer?: DevServerPlugin;
31
+ export?: ExportPlugin;
32
+ };
@@ -3,5 +3,5 @@ import http from 'http';
3
3
  import { ServerMessage } from 'react-cosmos-core';
4
4
  export declare function createMessageHandler(httpServer: http.Server): {
5
5
  sendMessage: (msg: ServerMessage) => void;
6
- cleanUp: () => void;
6
+ close: () => void;
7
7
  };
@@ -21,9 +21,9 @@ export function createMessageHandler(httpServer) {
21
21
  }
22
22
  });
23
23
  }
24
- function cleanUp() {
24
+ function close() {
25
25
  wss.clients.forEach(client => client.close());
26
26
  wss.close();
27
27
  }
28
- return { sendMessage, cleanUp };
28
+ return { sendMessage, close };
29
29
  }
@@ -1,24 +1,15 @@
1
1
  import path from 'path';
2
+ import { coreServerPlugins } from '../corePlugins/index.js';
2
3
  import { detectCosmosConfig, detectCosmosConfigPath, } from '../cosmosConfig/detectCosmosConfig.js';
3
4
  import { getPluginConfigs } from '../cosmosPlugin/pluginConfigs.js';
5
+ import { importServerPlugins } from '../shared/importServerPlugins.js';
4
6
  import { logPluginInfo } from '../shared/logPluginInfo.js';
5
- import { requirePluginModule } from '../shared/requirePluginModule.js';
6
7
  import { serveStaticDir } from '../shared/staticServer.js';
7
- import { httpProxyDevServerPlugin } from './corePlugins/httpProxy.js';
8
- import openFileDevServerPlugin from './corePlugins/openFile.js';
9
- import pluginEndpointDevServerPlugin from './corePlugins/pluginEndpoint.js';
10
- import { userDepsFileDevServerPlugin } from './corePlugins/userDepsFile.js';
11
8
  import { createExpressApp } from './expressApp.js';
12
9
  import { createHttpServer } from './httpServer.js';
13
10
  import { createMessageHandler } from './messageHandler.js';
14
- const builtInPlugins = [
15
- userDepsFileDevServerPlugin,
16
- httpProxyDevServerPlugin,
17
- openFileDevServerPlugin,
18
- pluginEndpointDevServerPlugin,
19
- ];
20
11
  export async function startDevServer(platformType) {
21
- const cosmosConfig = await detectCosmosConfig();
12
+ let cosmosConfig = await detectCosmosConfig();
22
13
  logCosmosConfigInfo();
23
14
  const pluginConfigs = await getPluginConfigs({
24
15
  cosmosConfig,
@@ -28,19 +19,36 @@ export async function startDevServer(platformType) {
28
19
  relativePaths: false,
29
20
  });
30
21
  logPluginInfo(pluginConfigs);
22
+ const userPlugins = await importServerPlugins(pluginConfigs, cosmosConfig.rootDir);
23
+ const plugins = [...coreServerPlugins, ...userPlugins];
24
+ for (const plugin of plugins) {
25
+ if (plugin.config) {
26
+ try {
27
+ cosmosConfig = await plugin.config({ cosmosConfig, platformType });
28
+ }
29
+ catch (err) {
30
+ console.log(`[Cosmos][plugin:${plugin.name}] Config hook failed`);
31
+ throw err;
32
+ }
33
+ }
34
+ }
31
35
  const app = await createExpressApp(platformType, cosmosConfig, pluginConfigs);
32
36
  const httpServer = await createHttpServer(cosmosConfig, app);
33
37
  const msgHandler = createMessageHandler(httpServer.server);
38
+ // Make Playground available as soon as possible and show a loading screen
39
+ // while plugins are initializing
40
+ await httpServer.start();
34
41
  const pluginCleanupCallbacks = [];
35
42
  async function cleanUp() {
36
43
  await Promise.all(pluginCleanupCallbacks.map(cleanup => cleanup()));
44
+ msgHandler.close();
37
45
  await httpServer.stop();
38
- msgHandler.cleanUp();
39
46
  }
40
- const userPlugins = await getDevServerPlugins(pluginConfigs, cosmosConfig.rootDir);
41
- for (const plugin of [...builtInPlugins, ...userPlugins]) {
47
+ for (const plugin of plugins) {
42
48
  try {
43
- const pluginReturn = await plugin({
49
+ if (!plugin.devServer)
50
+ continue;
51
+ const pluginReturn = await plugin.devServer({
44
52
  cosmosConfig,
45
53
  platformType,
46
54
  httpServer: httpServer.server,
@@ -55,7 +63,7 @@ export async function startDevServer(platformType) {
55
63
  catch (err) {
56
64
  // Log when a plugin fails to clean up, but continue to attempt
57
65
  // to clean up the remaining plugins
58
- console.log(`[Cosmos][${plugin.name}] Dev server plugin cleanup failed`);
66
+ console.log(`[Cosmos][plugin:${plugin.name}] Dev server cleanup failed`);
59
67
  console.log(err);
60
68
  }
61
69
  });
@@ -64,7 +72,7 @@ export async function startDevServer(platformType) {
64
72
  catch (err) {
65
73
  // Abort starting server if a plugin init fails and attempt cleanup of all
66
74
  // plugins that have already initialized
67
- console.log(`[Cosmos][${plugin.name}] Dev server plugin init failed`);
75
+ console.log(`[Cosmos][plugin:${plugin.name}] Dev server init failed`);
68
76
  cleanUp();
69
77
  throw err;
70
78
  }
@@ -72,7 +80,6 @@ export async function startDevServer(platformType) {
72
80
  if (cosmosConfig.staticPath) {
73
81
  serveStaticDir(app, cosmosConfig.staticPath, cosmosConfig.publicUrl);
74
82
  }
75
- await httpServer.start();
76
83
  return cleanUp;
77
84
  }
78
85
  function logCosmosConfigInfo() {
@@ -84,8 +91,3 @@ function logCosmosConfigInfo() {
84
91
  const relConfigPath = path.relative(process.cwd(), cosmosConfigPath);
85
92
  console.log(`[Cosmos] Using cosmos config found at ${relConfigPath}`);
86
93
  }
87
- async function getDevServerPlugins(pluginConfigs, rootDir) {
88
- return Promise.all(pluginConfigs
89
- .filter(pluginConfig => pluginConfig.devServer)
90
- .map(pluginConfig => requirePluginModule(rootDir, pluginConfig, 'devServer')));
91
- }
@@ -1,16 +1,17 @@
1
1
  import fs from 'fs/promises';
2
2
  import path from 'path';
3
3
  import { removeLeadingSlash, } from 'react-cosmos-core';
4
+ import { coreServerPlugins } from '../corePlugins/index.js';
4
5
  import { detectCosmosConfig } from '../cosmosConfig/detectCosmosConfig.js';
5
6
  import { getPluginConfigs } from '../cosmosPlugin/pluginConfigs.js';
7
+ import { importServerPlugins } from '../shared/importServerPlugins.js';
6
8
  import { logPluginInfo } from '../shared/logPluginInfo.js';
7
9
  import { getExportPlaygroundHtml } from '../shared/playgroundHtml.js';
8
- import { requirePluginModule } from '../shared/requirePluginModule.js';
9
10
  import { getStaticPath } from '../shared/staticPath.js';
10
11
  import { resolve } from '../utils/resolve.js';
11
- const builtInPlugins = [];
12
12
  export async function generateExport() {
13
- const cosmosConfig = await detectCosmosConfig();
13
+ const platformType = 'web';
14
+ let cosmosConfig = await detectCosmosConfig();
14
15
  const pluginConfigs = await getPluginConfigs({
15
16
  cosmosConfig,
16
17
  // Relative paths work in exports because all plugin modules are copied
@@ -18,19 +19,34 @@ export async function generateExport() {
18
19
  relativePaths: true,
19
20
  });
20
21
  logPluginInfo(pluginConfigs);
22
+ const userPlugins = await importServerPlugins(pluginConfigs, cosmosConfig.rootDir);
23
+ const plugins = [...coreServerPlugins, ...userPlugins];
24
+ for (const plugin of plugins) {
25
+ if (plugin.config) {
26
+ try {
27
+ cosmosConfig = await plugin.config({ cosmosConfig, platformType });
28
+ }
29
+ catch (err) {
30
+ console.log(`[Cosmos][plugin:${plugin.name}] Config hook failed`);
31
+ throw err;
32
+ }
33
+ }
34
+ }
21
35
  // Clear previous export (or other files at export path)
22
36
  const { exportPath } = cosmosConfig;
23
37
  await fs.rm(exportPath, { recursive: true, force: true });
38
+ await fs.mkdir(exportPath, { recursive: true });
24
39
  // Copy static assets first, so that the built index.html overrides the its
25
40
  // template file (in case the static assets are served from the root path)
26
41
  await copyStaticAssets(cosmosConfig);
27
- const userPlugins = await getExportPlugins(pluginConfigs, cosmosConfig.rootDir);
28
- for (const plugin of [...builtInPlugins, ...userPlugins]) {
42
+ for (const plugin of plugins) {
43
+ if (!plugin.export)
44
+ continue;
29
45
  try {
30
- await plugin({ cosmosConfig });
46
+ await plugin.export({ cosmosConfig });
31
47
  }
32
48
  catch (err) {
33
- console.log(`[Cosmos][${plugin.name}] Export plugin failed`);
49
+ console.log(`[Cosmos][plugin:${plugin.name}] Export failed`);
34
50
  throw err;
35
51
  }
36
52
  }
@@ -59,11 +75,6 @@ async function copyStaticAssets(cosmosConfig) {
59
75
  const exportStaticPath = path.resolve(exportPath, removeLeadingSlash(publicUrl));
60
76
  fs.cp(staticPath, exportStaticPath, { recursive: true });
61
77
  }
62
- async function getExportPlugins(pluginConfigs, rootDir) {
63
- return Promise.all(pluginConfigs
64
- .filter(pluginConfig => pluginConfig.export)
65
- .map(pluginConfig => requirePluginModule(rootDir, pluginConfig, 'export')));
66
- }
67
78
  async function exportPlaygroundFiles(cosmosConfig, pluginConfigs) {
68
79
  const { exportPath } = cosmosConfig;
69
80
  // Copy UI plugins to export path and embed them in the playground HTML
@@ -1,7 +1,7 @@
1
1
  import path from 'path';
2
2
  import { createFixtureTree, flattenFixtureTree, getDecoratedFixtureElement, getFixtureListFromExports, getSortedDecoratorsForFixturePath, stringifyPlaygroundUrlQuery, stringifyRendererUrlQuery, } from 'react-cosmos-core';
3
3
  import { RENDERER_FILENAME } from '../shared/playgroundHtml.js';
4
- import { resolveUrlPath } from '../shared/resolveUrlPath.js';
4
+ import { resolveRendererUrl } from '../shared/resolveRendererUrl.js';
5
5
  import { getUserModules } from '../userDeps/getUserModules.js';
6
6
  export function getFixtures(cosmosConfig) {
7
7
  const { fixturesDir, fixtureFileSuffix, rootDir } = cosmosConfig;
@@ -47,8 +47,8 @@ function getRendererUrl(cosmosConfig, fixtureId) {
47
47
  if (rendererUrl)
48
48
  return `${rendererUrl}?${query}`;
49
49
  const host = getPlaygroundHost(cosmosConfig);
50
- const urlPath = resolveUrlPath(publicUrl, RENDERER_FILENAME);
51
- return `${host}${urlPath}?${query}`;
50
+ const urlPath = resolveRendererUrl(publicUrl, RENDERER_FILENAME);
51
+ return new URL(`${urlPath}?${query}`, host).toString();
52
52
  }
53
53
  function getPlaygroundHost({ hostname, port, https }) {
54
54
  return `${https ? 'https' : 'http'}://${hostname || 'localhost'}:${port}`;
package/dist/index.d.ts CHANGED
@@ -0,0 +1,21 @@
1
+ export * from './cosmosConfig/createCosmosConfig.js';
2
+ export * from './cosmosConfig/detectCosmosConfig.js';
3
+ export * from './cosmosConfig/getCosmosConfigAtPath.js';
4
+ export * from './cosmosConfig/types.js';
5
+ export * from './cosmosPlugin/findCosmosPluginConfigs.js';
6
+ export * from './cosmosPlugin/pluginConfigs.js';
7
+ export * from './cosmosPlugin/types.js';
8
+ export * from './getFixtures/getFixtures.js';
9
+ export * from './shared/findNextAvailablePort.js';
10
+ export { RENDERER_FILENAME } from './shared/playgroundHtml.js';
11
+ export * from './shared/playgroundUrl.js';
12
+ export * from './shared/staticServer.js';
13
+ export * from './testHelpers/cwd.js';
14
+ export * from './userDeps/fixtureWatcher.js';
15
+ export * from './userDeps/generateUserDepsModule.js';
16
+ export * from './utils/cli.js';
17
+ export * from './utils/fs.js';
18
+ export * from './utils/requireSilent.js';
19
+ export * from './utils/resolve.js';
20
+ export * from './utils/resolveLoose.js';
21
+ export * from './utils/resolveSilent.js';