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
@@ -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,13 +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
- );
9
-
10
- // Auto disable Fast Refresh in CRA 4 until integration is implemented
11
- // https://github.com/react-cosmos/react-cosmos/issues/1272
12
- process.env.FAST_REFRESH = process.env.FAST_REFRESH || false;
6
+ const { startDevServer } = await import('../dist/devServer/startDevServer.js');
13
7
 
14
8
  startDevServer('web').catch(err => {
15
9
  console.log('[Cosmos] Server crashed...');
package/client.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './dist/client.js';
package/client.js ADDED
@@ -0,0 +1 @@
1
+ export * from './dist/client.js';
@@ -1,7 +1,5 @@
1
1
  {
2
- "$schema": "http://json-schema.org/draft-04/schema",
3
- "title": "JSON schema for React Cosmos configs",
4
- "type": "object",
2
+ "$schema": "http://json-schema.org/draft-04/schema#",
5
3
  "additionalProperties": false,
6
4
  "properties": {
7
5
  "$schema": {
@@ -22,7 +20,7 @@
22
20
  "type": "boolean"
23
21
  },
24
22
  "disablePlugins": {
25
- "description": "Disable all plugins 3rd party plugins",
23
+ "description": "Disable plugins",
26
24
  "type": "boolean"
27
25
  },
28
26
  "staticPath": {
@@ -37,7 +35,7 @@
37
35
  "uniqueItems": true
38
36
  },
39
37
  "publicUrl": {
40
- "description": "Base URL for static assets. [default: \"/\"]",
38
+ "description": "Base URL for static assets. [default: \"\"]",
41
39
  "type": "string"
42
40
  },
43
41
  "fixturesDir": {
@@ -65,10 +63,13 @@
65
63
  },
66
64
  "uniqueItems": true
67
65
  },
68
- "userDepsFilePath": {
69
- "description": "Where to generate a file that contains a map to all fixtures and other Cosmos-related user modules. Only used in setups where Cosmos can't piggyback on the user's build (eg. React Native setups). [default: \"cosmos.userdeps.js\"]",
70
- "type": "string",
71
- "minLength": 1
66
+ "lazy": {
67
+ "description": "Dynamically import fixture and decorator modules as they are loaded. When false all fixture and decorator modules are imported statically and bundled together. [default: false]",
68
+ "type": "boolean"
69
+ },
70
+ "exposeImports": {
71
+ "description": "Expose user imports and config required for the Cosmos renderer. Used with React Native and in custom integrations. When a path is specified it requires a file extension (eg. \"src/cosmos.imports.ts\"). [default: false]",
72
+ "anyOf": [{ "type": "string", "minLength": 1 }, { "type": "boolean" }]
72
73
  },
73
74
  "hostname": {
74
75
  "description": "Dev server hostname. Set to null to accept connections with any hostname. [default: null]",
@@ -78,12 +79,16 @@
78
79
  "description": "Dev server port. [default: 5000]",
79
80
  "type": "number"
80
81
  },
82
+ "portRetries": {
83
+ "description": "Max number of port retries. [default: 10]",
84
+ "type": "number"
85
+ },
81
86
  "https": {
82
- "description": "Server will be served over HTTPS",
87
+ "description": "Server will be served over HTTPS.",
83
88
  "type": "boolean"
84
89
  },
85
90
  "httpsOptions": {
86
- "description": "Additional options for HTTPS server",
91
+ "description": "Additional options for HTTPS server.",
87
92
  "type": "object",
88
93
  "additionalProperties": false,
89
94
  "properties": {
@@ -135,7 +140,19 @@
135
140
  },
136
141
  "rendererUrl": {
137
142
  "description": "Required when renderer doesn't run on the same port (or host) as the Playground. Useful for integrations with build tools. [default: null]",
138
- "anyOf": [{ "type": "string", "minLength": 1 }, { "type": "null" }]
143
+ "anyOf": [
144
+ { "type": "string", "minLength": 1 },
145
+ {
146
+ "type": "object",
147
+ "additionalProperties": false,
148
+ "required": ["dev", "export"],
149
+ "properties": {
150
+ "dev": { "type": "string", "minLength": 1 },
151
+ "export": { "type": "string", "minLength": 1 }
152
+ }
153
+ },
154
+ { "type": "null" }
155
+ ]
139
156
  },
140
157
  "dom": {
141
158
  "description": "DOM-related options",
@@ -148,17 +165,36 @@
148
165
  }
149
166
  }
150
167
  },
168
+ "vite": {
169
+ "description": "Vite-related options",
170
+ "type": "object",
171
+ "additionalProperties": false,
172
+ "properties": {
173
+ "configPath": {
174
+ "description": "Path to Vite config. Set to false to disable reading it from the default path. [default: \"vite.config.js\"]",
175
+ "anyOf": [{ "type": "string", "minLength": 1 }, { "enum": [false] }]
176
+ },
177
+ "indexPath": {
178
+ "description": "Path to index module (eg. \"src/my-index.tsx\"). [default: matches common index/main module paths]",
179
+ "anyOf": [{ "type": "string", "minLength": 1 }, { "type": "null" }]
180
+ },
181
+ "port": {
182
+ "description": "Vite renderer port. [default: 5050]",
183
+ "type": "number"
184
+ }
185
+ }
186
+ },
151
187
  "webpack": {
152
188
  "description": "Webpack-related options",
153
189
  "type": "object",
154
190
  "additionalProperties": false,
155
191
  "properties": {
156
192
  "configPath": {
157
- "description": "Path to an existing webpack config, which Cosmos will reuse to build your code. Set to null to disable this behavior. [default \"webpack.config.js\"]",
193
+ "description": "Path to an existing webpack config, which Cosmos will reuse to build your code. Set to null to disable this behavior. [default: \"webpack.config.js\"]",
158
194
  "anyOf": [{ "type": "string", "minLength": 1 }, { "type": "null" }]
159
195
  },
160
196
  "overridePath": {
161
- "description": "Path to a user module that customizes the webpack config used by Cosmos. Set to null to disable this behavior. [default \"webpack.override.js\"]",
197
+ "description": "Path to a user module that customizes the webpack config used by Cosmos. Set to null to disable this behavior. [default: \"webpack.override.js\"]",
162
198
  "anyOf": [{ "type": "string", "minLength": 1 }, { "type": "null" }]
163
199
  },
164
200
  "includeHashInOutputFilename": {
@@ -202,5 +238,7 @@
202
238
  }
203
239
  }
204
240
  }
205
- }
241
+ },
242
+ "title": "JSON schema for React Cosmos configs",
243
+ "type": "object"
206
244
  }
@@ -0,0 +1,7 @@
1
+ // CJS mock for packages/react-cosmos/src/utils/requireModule.ts
2
+ export function requireModule(moduleId) {
3
+ return require(moduleId);
4
+ }
5
+ export function requireFrom(fromDirectory, moduleId) {
6
+ return require(require.resolve(moduleId, { paths: [fromDirectory] }));
7
+ }
@@ -0,0 +1,7 @@
1
+ // CJS mock for packages/react-cosmos/src/utils/resolve.ts
2
+ export function resolve(moduleId) {
3
+ return require.resolve(moduleId);
4
+ }
5
+ export function resolveFrom(fromDirectory, moduleId) {
6
+ return require.resolve(moduleId, { paths: [fromDirectory] });
7
+ }
@@ -0,0 +1,4 @@
1
+ // CJS mock for packages/react-cosmos/src/shared/staticPath.ts
2
+ export function getStaticPath(relPath) {
3
+ return require.resolve(`../static/${relPath}`);
4
+ }
@@ -0,0 +1 @@
1
+ export { Viewport, useSelect, useValue } from 'react-cosmos-renderer/client';
package/dist/client.js ADDED
@@ -0,0 +1 @@
1
+ export { Viewport, useSelect, useValue } from 'react-cosmos-renderer/client';
@@ -0,0 +1,2 @@
1
+ import { CosmosServerPlugin } from '../cosmosPlugin/types.js';
2
+ export declare const exposeImportsServerPlugin: CosmosServerPlugin;
@@ -0,0 +1,53 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { pickRendererUrl, } from 'react-cosmos-core';
4
+ import { getPlaygroundUrl } from '../shared/playgroundUrl.js';
5
+ import { startFixtureWatcher } from '../userModules/fixtureWatcher.js';
6
+ import { generateUserImports } from '../userModules/generateUserImports.js';
7
+ import { moduleExists } from '../utils/fs.js';
8
+ export const exposeImportsServerPlugin = {
9
+ name: 'exposeImports',
10
+ async devServer({ cosmosConfig, platform }) {
11
+ if (!shouldExposeImports(platform, cosmosConfig))
12
+ return;
13
+ await generateImportsFile(cosmosConfig, 'dev');
14
+ const watcher = await startFixtureWatcher(cosmosConfig, 'all', () => {
15
+ generateImportsFile(cosmosConfig, 'dev');
16
+ });
17
+ return () => {
18
+ watcher.close();
19
+ };
20
+ },
21
+ async export({ cosmosConfig }) {
22
+ if (shouldExposeImports('web', cosmosConfig)) {
23
+ await generateImportsFile(cosmosConfig, 'export');
24
+ }
25
+ },
26
+ };
27
+ function shouldExposeImports(platform, cosmosConfig) {
28
+ return platform === 'native' || Boolean(cosmosConfig.exposeImports);
29
+ }
30
+ async function generateImportsFile(cosmosConfig, command) {
31
+ const { exposeImports } = cosmosConfig;
32
+ const filePath = typeof exposeImports === 'string'
33
+ ? exposeImports
34
+ : getDefaultFilePath(cosmosConfig.rootDir);
35
+ const typeScript = /\.tsx?$/.test(filePath);
36
+ const rendererConfig = {
37
+ playgroundUrl: getPlaygroundUrl(cosmosConfig),
38
+ rendererUrl: pickRendererUrl(cosmosConfig.rendererUrl, command),
39
+ };
40
+ const fileSource = generateUserImports({
41
+ cosmosConfig,
42
+ rendererConfig,
43
+ relativeToDir: path.dirname(filePath),
44
+ typeScript,
45
+ });
46
+ await fs.writeFile(filePath, fileSource, 'utf8');
47
+ const relModulesPath = path.relative(process.cwd(), filePath);
48
+ console.log(`[Cosmos] Generated ${relModulesPath}`);
49
+ }
50
+ function getDefaultFilePath(rootDir) {
51
+ const ext = moduleExists('typescript') ? 'ts' : 'js';
52
+ return path.join(rootDir, `cosmos.imports.${ext}`);
53
+ }
@@ -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({ cosmosConfig, platform, expressApp }) {
5
+ if (platform !== '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 { exposeImportsServerPlugin } from './exposeImports.js';
2
+ import { httpProxyServerPlugin } from './httpProxy.js';
3
+ import { openFileServerPlugin } from './openFile.js';
4
+ import { pluginEndpointServerPlugin } from './pluginEndpoint.js';
5
+ import { portRetryServerPlugin } from './portRetry.js';
6
+ export const coreServerPlugins = [
7
+ portRetryServerPlugin,
8
+ exposeImportsServerPlugin,
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,59 @@
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 => {
30
+ console.log(err);
31
+ res.status(500).send('Failed to open file');
32
+ })
33
+ .then(() => res.send());
34
+ });
35
+ },
36
+ };
37
+ function getReqQuery(req) {
38
+ const { filePath, line, column } = req.query;
39
+ if (typeof filePath !== 'string')
40
+ throw new Error('filePath missing');
41
+ return {
42
+ filePath,
43
+ line: typeof line === 'string' ? parseInt(line, 10) : 1,
44
+ column: typeof column === 'string' ? parseInt(column, 10) : 1,
45
+ };
46
+ }
47
+ function resolveFilePath(rootDir, filePath) {
48
+ // This heuristic is needed because the open file endpoint is used for
49
+ // multiple applications, which provide different file path types:
50
+ // 1. Edit fixture button: Sends path relative to Cosmos rootDir
51
+ // 2. react-error-overlay runtime error: Sends absolute path
52
+ // 3. react-error-overlay compile error: Sends path relative to CWD
53
+ if (path.isAbsolute(filePath)) {
54
+ return filePath;
55
+ }
56
+ const cosmosRelPath = path.join(rootDir, filePath);
57
+ const cwdRelPath = path.join(process.cwd(), filePath);
58
+ return fs.existsSync(cosmosRelPath) ? cosmosRelPath : cwdRelPath;
59
+ }
@@ -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({ 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,14 @@
1
+ import { findNextAvailablePort } from '../shared/findNextAvailablePort.js';
2
+ export const portRetryServerPlugin = {
3
+ name: 'portRetry',
4
+ async config({ cosmosConfig, command }) {
5
+ if (command === 'export') {
6
+ return cosmosConfig;
7
+ }
8
+ const { port, portRetries } = cosmosConfig;
9
+ return {
10
+ ...cosmosConfig,
11
+ port: portRetries ? await findNextAvailablePort(port, portRetries) : port,
12
+ };
13
+ },
14
+ };
@@ -5,9 +5,10 @@ export function createCosmosConfig(rootDir, cosmosConfigInput = {}) {
5
5
  return {
6
6
  ...cosmosConfigInput,
7
7
  rootDir,
8
- exportPath: getExportPath(cosmosConfigInput, rootDir),
9
8
  detectLocalPlugins: cosmosConfigInput.detectLocalPlugins ?? true,
10
9
  disablePlugins: cosmosConfigInput.disablePlugins ?? false,
10
+ exposeImports: getExposeImports(cosmosConfigInput, rootDir),
11
+ exportPath: getExportPath(cosmosConfigInput, rootDir),
11
12
  fixtureFileSuffix: getFixtureFileSuffix(cosmosConfigInput),
12
13
  fixturesDir: getFixturesDir(cosmosConfigInput),
13
14
  globalImports: getGlobalImports(cosmosConfigInput, rootDir),
@@ -15,13 +16,15 @@ export function createCosmosConfig(rootDir, cosmosConfigInput = {}) {
15
16
  https: getHttps(cosmosConfigInput),
16
17
  httpsOptions: getHttpsOptions(cosmosConfigInput, rootDir),
17
18
  ignore: getIgnore(cosmosConfigInput),
18
- port: getPort(cosmosConfigInput),
19
+ lazy: getLazy(cosmosConfigInput),
19
20
  plugins: getPlugins(cosmosConfigInput, rootDir),
20
- publicUrl: getPublicUrl(cosmosConfigInput),
21
+ port: getPort(cosmosConfigInput),
22
+ portRetries: getPortRetries(cosmosConfigInput),
23
+ publicUrl: cosmosConfigInput.publicUrl ?? '',
24
+ rendererUrl: cosmosConfigInput.rendererUrl ?? null,
21
25
  staticPath: getStaticPath(cosmosConfigInput, rootDir),
22
- userDepsFilePath: getUserDepsFilePath(cosmosConfigInput, rootDir),
23
26
  watchDirs: getWatchDirs(cosmosConfigInput, rootDir),
24
- rendererUrl: cosmosConfigInput.rendererUrl ?? null,
27
+ dom: getDomConfig(cosmosConfigInput.dom || {}),
25
28
  ui: cosmosConfigInput.ui || {},
26
29
  };
27
30
  }
@@ -50,9 +53,6 @@ function getHttpsOptions(cosmosConfigInput, rootDir) {
50
53
  function getIgnore({ ignore = [] }) {
51
54
  return ['**/node_modules/**', ...ignore];
52
55
  }
53
- function getPublicUrl({ publicUrl = '/' }) {
54
- return publicUrl;
55
- }
56
56
  function getFixturesDir({ fixturesDir = '__fixtures__' }) {
57
57
  return fixturesDir;
58
58
  }
@@ -63,9 +63,18 @@ function getWatchDirs(cosmosConfigInput, rootDir) {
63
63
  const { watchDirs = ['.'] } = cosmosConfigInput;
64
64
  return watchDirs.map(watchDir => path.resolve(rootDir, watchDir));
65
65
  }
66
- function getUserDepsFilePath(cosmosConfigInput, rootDir) {
67
- const { userDepsFilePath = 'cosmos.userdeps.js' } = cosmosConfigInput;
68
- return path.resolve(rootDir, userDepsFilePath);
66
+ function getExposeImports(cosmosConfigInput, rootDir) {
67
+ const cliArgs = getCliArgs();
68
+ if (typeof cliArgs.exposeImports === 'boolean') {
69
+ return cliArgs.exposeImports;
70
+ }
71
+ else if (typeof cliArgs.exposeImports === 'string') {
72
+ return path.resolve(rootDir, cliArgs.exposeImports);
73
+ }
74
+ const { exposeImports = false } = cosmosConfigInput;
75
+ return typeof exposeImports === 'string'
76
+ ? path.resolve(rootDir, exposeImports)
77
+ : exposeImports;
69
78
  }
70
79
  function getHostname({ hostname = null }) {
71
80
  return hostname;
@@ -78,6 +87,9 @@ function getPort(cosmosConfigInput) {
78
87
  const { port = 5000 } = cosmosConfigInput;
79
88
  return port;
80
89
  }
90
+ function getPortRetries({ portRetries = 10 }) {
91
+ return portRetries;
92
+ }
81
93
  function getGlobalImports(cosmosConfigInput, rootDir) {
82
94
  const { globalImports = [] } = cosmosConfigInput;
83
95
  return globalImports.map(globalImport => resolveLoose(rootDir, globalImport));
@@ -86,3 +98,17 @@ function getPlugins(cosmosConfigInput, rootDir) {
86
98
  const { plugins = [] } = cosmosConfigInput;
87
99
  return plugins.map(plugin => resolveLoose(rootDir, plugin));
88
100
  }
101
+ function getDomConfig(cosmosConfigInput) {
102
+ const { containerQuerySelector = null } = cosmosConfigInput;
103
+ return {
104
+ containerQuerySelector,
105
+ };
106
+ }
107
+ function getLazy(cosmosConfigInput) {
108
+ const cliArgs = getCliArgs();
109
+ if (typeof cliArgs.lazy === 'boolean') {
110
+ return cliArgs.lazy;
111
+ }
112
+ const { lazy = false } = cosmosConfigInput;
113
+ return lazy;
114
+ }
@@ -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,10 +2,15 @@ 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;
13
+ exposeImports: boolean | string;
9
14
  fixtureFileSuffix: string;
10
15
  fixturesDir: string;
11
16
  globalImports: string[];
@@ -13,18 +18,23 @@ export type CosmosConfig = {
13
18
  https: boolean;
14
19
  httpsOptions: null | HttpsOptions;
15
20
  ignore: string[];
21
+ lazy: boolean;
16
22
  port: number;
23
+ portRetries: number;
17
24
  plugins: string[];
18
25
  publicUrl: string;
19
- rendererUrl: string | null;
26
+ rendererUrl: null | string | {
27
+ dev: string;
28
+ export: string;
29
+ };
20
30
  rootDir: string;
21
31
  staticPath: null | string;
22
- userDepsFilePath: string;
23
32
  watchDirs: string[];
24
33
  [option: string]: unknown;
25
34
  ui: {
26
35
  [pluginName: string]: {};
27
36
  };
28
37
  };
38
+ export type CosmosDomConfigInput = Partial<CosmosDomConfig>;
29
39
  export type CosmosConfigInput = Partial<CosmosConfig>;
30
40
  export {};
@@ -1,4 +1,4 @@
1
- import glob from 'glob';
1
+ import { globSync } from 'glob';
2
2
  import { readCosmosPluginConfig } from './readCosmosPluginConfig.js';
3
3
  export async function findCosmosPluginConfigs({ rootDir, relativePaths, ignore, }) {
4
4
  const configPaths = findCosmosPluginConfigPaths(rootDir, ignore);
@@ -6,7 +6,7 @@ export async function findCosmosPluginConfigs({ rootDir, relativePaths, ignore,
6
6
  }
7
7
  const defaultIgnore = ['**/node_modules/**'];
8
8
  function findCosmosPluginConfigPaths(rootDir, ignore = defaultIgnore) {
9
- return glob.sync('**/cosmos.plugin.json', {
9
+ return globSync('**/cosmos.plugin.json', {
10
10
  cwd: rootDir,
11
11
  absolute: true,
12
12
  ignore,
@@ -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
  }
@@ -1,12 +1,18 @@
1
1
  /// <reference types="node" />
2
2
  import express from 'express';
3
3
  import http from 'http';
4
- import { MessageType } from 'react-cosmos-core';
4
+ import { CosmosCommand, MessageType } from 'react-cosmos-core';
5
5
  import { CosmosConfig } from '../cosmosConfig/types.js';
6
- export type PlatformType = 'web' | 'native';
6
+ export type CosmosPlatform = 'web' | 'native';
7
+ export type CosmosConfigPluginArgs = {
8
+ cosmosConfig: CosmosConfig;
9
+ command: CosmosCommand;
10
+ platform: CosmosPlatform;
11
+ };
12
+ export type CosmosConfigPlugin = (args: CosmosConfigPluginArgs) => Promise<CosmosConfig> | CosmosConfig;
7
13
  export type DevServerPluginArgs = {
8
14
  cosmosConfig: CosmosConfig;
9
- platformType: PlatformType;
15
+ platform: CosmosPlatform;
10
16
  httpServer: http.Server;
11
17
  expressApp: express.Express;
12
18
  sendMessage(msg: MessageType): unknown;
@@ -19,3 +25,9 @@ export type ExportPluginArgs = {
19
25
  cosmosConfig: CosmosConfig;
20
26
  };
21
27
  export type ExportPlugin = (args: ExportPluginArgs) => unknown;
28
+ export type CosmosServerPlugin = {
29
+ name: string;
30
+ config?: CosmosConfigPlugin;
31
+ devServer?: DevServerPlugin;
32
+ export?: ExportPlugin;
33
+ };
@@ -0,0 +1,5 @@
1
+ import express from 'express';
2
+ import { CosmosPluginConfig } from 'react-cosmos-core';
3
+ import { CosmosConfig } from '../cosmosConfig/types.js';
4
+ import { CosmosPlatform } from '../cosmosPlugin/types.js';
5
+ export declare function createExpressApp(platform: CosmosPlatform, cosmosConfig: CosmosConfig, pluginConfigs: CosmosPluginConfig[]): Promise<express.Express>;