@storybook/core-server 6.4.0-beta.8 → 6.4.0-rc.2

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 (73) hide show
  1. package/dist/cjs/build-dev.js +1 -0
  2. package/dist/cjs/build-static.js +25 -3
  3. package/dist/cjs/cli/utils.js +21 -3
  4. package/dist/cjs/dev-server.js +4 -1
  5. package/dist/cjs/presets/common-preset.js +2 -1
  6. package/dist/cjs/utils/StoryIndexGenerator.js +16 -10
  7. package/dist/cjs/utils/__mockdata__/src/NoMeta.stories.js +12 -0
  8. package/dist/cjs/utils/copy-all-static-files.js +33 -0
  9. package/dist/cjs/utils/get-manager-builder.js +6 -3
  10. package/dist/cjs/utils/get-preview-builder.js +13 -4
  11. package/dist/cjs/utils/get-server-channel.js +56 -0
  12. package/dist/cjs/utils/server-address.js +10 -2
  13. package/dist/cjs/utils/server-statics.js +37 -4
  14. package/dist/cjs/utils/stories-json.js +17 -11
  15. package/dist/cjs/utils/watch-story-specifiers.js +66 -10
  16. package/dist/esm/build-dev.js +2 -1
  17. package/dist/esm/build-static.js +25 -4
  18. package/dist/esm/cli/utils.js +22 -3
  19. package/dist/esm/dev-server.js +3 -1
  20. package/dist/esm/presets/common-preset.js +2 -1
  21. package/dist/esm/utils/StoryIndexGenerator.js +14 -8
  22. package/dist/esm/utils/__mockdata__/src/NoMeta.stories.js +4 -0
  23. package/dist/esm/utils/copy-all-static-files.js +27 -0
  24. package/dist/esm/utils/get-manager-builder.js +6 -3
  25. package/dist/esm/utils/get-preview-builder.js +13 -4
  26. package/dist/esm/utils/get-server-channel.js +39 -0
  27. package/dist/esm/utils/server-address.js +5 -0
  28. package/dist/esm/utils/server-statics.js +35 -4
  29. package/dist/esm/utils/stories-json.js +13 -9
  30. package/dist/esm/utils/watch-story-specifiers.js +61 -10
  31. package/dist/modern/build-dev.js +2 -1
  32. package/dist/modern/build-static.js +25 -4
  33. package/dist/modern/cli/utils.js +22 -3
  34. package/dist/modern/dev-server.js +3 -1
  35. package/dist/modern/presets/common-preset.js +2 -1
  36. package/dist/modern/utils/StoryIndexGenerator.js +14 -8
  37. package/dist/modern/utils/__mockdata__/src/NoMeta.stories.js +4 -0
  38. package/dist/modern/utils/copy-all-static-files.js +27 -0
  39. package/dist/modern/utils/get-manager-builder.js +6 -3
  40. package/dist/modern/utils/get-preview-builder.js +13 -4
  41. package/dist/modern/utils/get-server-channel.js +39 -0
  42. package/dist/modern/utils/server-address.js +5 -0
  43. package/dist/modern/utils/server-statics.js +35 -4
  44. package/dist/modern/utils/stories-json.js +13 -9
  45. package/dist/modern/utils/watch-story-specifiers.js +61 -10
  46. package/dist/ts3.4/cli/prod.d.ts +2 -15
  47. package/dist/ts3.4/cli/utils.d.ts +3 -5
  48. package/dist/ts3.4/presets/common-preset.d.ts +1 -0
  49. package/dist/ts3.4/utils/StoryIndexGenerator.d.ts +3 -3
  50. package/dist/ts3.4/utils/__mockdata__/src/NoMeta.stories.d.ts +1 -0
  51. package/dist/ts3.4/utils/copy-all-static-files.d.ts +1 -0
  52. package/dist/ts3.4/utils/get-server-channel.d.ts +9 -0
  53. package/dist/ts3.4/utils/server-address.d.ts +3 -0
  54. package/dist/ts3.4/utils/server-statics.d.ts +2 -3
  55. package/dist/ts3.4/utils/stories-json.d.ts +3 -1
  56. package/dist/ts3.4/utils/watch-story-specifiers.d.ts +3 -1
  57. package/dist/ts3.9/cli/prod.d.ts +2 -15
  58. package/dist/ts3.9/cli/utils.d.ts +3 -5
  59. package/dist/ts3.9/presets/common-preset.d.ts +1 -0
  60. package/dist/ts3.9/utils/StoryIndexGenerator.d.ts +3 -3
  61. package/dist/ts3.9/utils/__mockdata__/src/NoMeta.stories.d.ts +1 -0
  62. package/dist/ts3.9/utils/copy-all-static-files.d.ts +1 -0
  63. package/dist/ts3.9/utils/get-server-channel.d.ts +9 -0
  64. package/dist/ts3.9/utils/server-address.d.ts +3 -0
  65. package/dist/ts3.9/utils/server-statics.d.ts +2 -3
  66. package/dist/ts3.9/utils/stories-json.d.ts +3 -1
  67. package/dist/ts3.9/utils/watch-story-specifiers.d.ts +3 -1
  68. package/package.json +20 -14
  69. package/dist/cjs/utils/use-events-as-sse.js +0 -65
  70. package/dist/esm/utils/use-events-as-sse.js +0 -58
  71. package/dist/modern/utils/use-events-as-sse.js +0 -58
  72. package/dist/ts3.4/utils/use-events-as-sse.d.ts +0 -4
  73. package/dist/ts3.9/utils/use-events-as-sse.d.ts +0 -4
@@ -96,6 +96,7 @@ async function buildDevStandalone(options) {
96
96
  options.configType = 'DEVELOPMENT';
97
97
  options.configDir = _path.default.resolve(options.configDir);
98
98
  options.outputDir = options.smokeTest ? (0, _coreCommon.resolvePathInStorybookCache)('public') : _path.default.resolve(options.outputDir || (0, _coreCommon.resolvePathInStorybookCache)('public'));
99
+ options.serverChannelUrl = (0, _serverAddress.getServerChannelUrl)(port, options);
99
100
  /* eslint-enable no-param-reassign */
100
101
 
101
102
  var previewBuilder = await (0, _getPreviewBuilder.getPreviewBuilder)(options.configDir);
@@ -18,6 +18,8 @@ var _fsExtra = _interopRequireDefault(require("fs-extra"));
18
18
 
19
19
  var _path = _interopRequireDefault(require("path"));
20
20
 
21
+ var _tsDedent = _interopRequireDefault(require("ts-dedent"));
22
+
21
23
  var _nodeLogger = require("@storybook/node-logger");
22
24
 
23
25
  var _coreCommon = require("@storybook/core-common");
@@ -63,7 +65,7 @@ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { va
63
65
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
64
66
 
65
67
  async function buildStaticStandalone(options) {
66
- var _options$staticDir;
68
+ var _options$staticDir, _core$builder;
67
69
 
68
70
  /* eslint-disable no-param-reassign */
69
71
  options.configType = 'PRODUCTION';
@@ -90,13 +92,32 @@ async function buildStaticStandalone(options) {
90
92
 
91
93
  await _fsExtra.default.emptyDir(options.outputDir);
92
94
  await (0, _cpy.default)(defaultFavIcon, options.outputDir);
93
- await (0, _copyAllStaticFiles.copyAllStaticFiles)(options.staticDir, options.outputDir);
94
95
  var previewBuilder = await (0, _getPreviewBuilder.getPreviewBuilder)(options.configDir);
95
96
  var managerBuilder = await (0, _getManagerBuilder.getManagerBuilder)(options.configDir);
96
97
  var presets = (0, _coreCommon.loadAllPresets)(_objectSpread({
97
98
  corePresets: [require.resolve('./presets/common-preset'), ...managerBuilder.corePresets, ...previewBuilder.corePresets, require.resolve('./presets/babel-cache-preset')],
98
99
  overridePresets: previewBuilder.overridePresets
99
100
  }, options));
101
+ var staticDirs = await presets.apply('staticDirs');
102
+
103
+ if (staticDirs && options.staticDir) {
104
+ throw new Error((0, _tsDedent.default)`
105
+ Conflict when trying to read staticDirs:
106
+ * Storybook's configuration option: 'staticDirs'
107
+ * Storybook's CLI flag: '--staticDir' or '-s'
108
+
109
+ Choose one of them, but not both.
110
+ `);
111
+ }
112
+
113
+ if (staticDirs) {
114
+ await (0, _copyAllStaticFiles.copyAllStaticFilesRelativeToMain)(staticDirs, options.outputDir, options.configDir);
115
+ }
116
+
117
+ if (options.staticDir) {
118
+ await (0, _copyAllStaticFiles.copyAllStaticFiles)(options.staticDir, options.outputDir);
119
+ }
120
+
100
121
  var features = await presets.apply('features');
101
122
 
102
123
  if (features !== null && features !== void 0 && features.buildStoriesJson || features !== null && features !== void 0 && features.storyStoreV7) {
@@ -121,8 +142,9 @@ async function buildStaticStandalone(options) {
121
142
  }
122
143
 
123
144
  var core = await presets.apply('core');
145
+ var builderName = typeof (core === null || core === void 0 ? void 0 : core.builder) === 'string' ? core.builder : core === null || core === void 0 ? void 0 : (_core$builder = core.builder) === null || _core$builder === void 0 ? void 0 : _core$builder.name;
124
146
 
125
- var _ref = (core === null || core === void 0 ? void 0 : core.builder) === 'webpack5' ? await Promise.resolve().then(function () {
147
+ var _ref = builderName === 'webpack5' ? await Promise.resolve().then(function () {
126
148
  return _interopRequireWildcard(require('@storybook/manager-webpack5/prebuilt-manager'));
127
149
  }) : await Promise.resolve().then(function () {
128
150
  return _interopRequireWildcard(require('@storybook/manager-webpack4/prebuilt-manager'));
@@ -32,14 +32,32 @@ function getEnvConfig(program, configEnv) {
32
32
  });
33
33
  }
34
34
 
35
- var warnDLLsDeprecated = (0, _utilDeprecate.default)(function () {}, (0, _tsDedent.default)`
35
+ var warnDeprecatedFlag = function (message) {
36
+ return (0, _utilDeprecate.default)(function () {}, (0, _tsDedent.default)(message));
37
+ };
38
+
39
+ var warnDLLsDeprecated = warnDeprecatedFlag(`
36
40
  DLL-related CLI flags are deprecated, see:
37
41
 
38
42
  https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#deprecated-dll-flags
39
43
  `);
44
+ var warnStaticDirDeprecated = warnDeprecatedFlag(`
45
+ --static-dir CLI flag is deprecated, see:
46
+
47
+ https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#deprecated-static-dir-flag
48
+ `);
40
49
 
41
- function checkDeprecatedFlags(options) {
42
- if (!options.dll || options.uiDll || options.docsDll) {
50
+ function checkDeprecatedFlags({
51
+ dll: dll,
52
+ uiDll: uiDll,
53
+ docsDll: docsDll,
54
+ staticDir: staticDir
55
+ }) {
56
+ if (!dll || uiDll || docsDll) {
43
57
  warnDLLsDeprecated();
44
58
  }
59
+
60
+ if (staticDir) {
61
+ warnStaticDirDeprecated();
62
+ }
45
63
  }
@@ -26,6 +26,8 @@ var _serverStatics = require("./utils/server-statics");
26
26
 
27
27
  var _storiesJson = require("./utils/stories-json");
28
28
 
29
+ var _getServerChannel = require("./utils/get-server-channel");
30
+
29
31
  var _openInBrowser = require("./utils/open-in-browser");
30
32
 
31
33
  var _getPreviewBuilder = require("./utils/get-preview-builder");
@@ -58,6 +60,7 @@ async function storybookDevServer(options) {
58
60
  var startTime = process.hrtime();
59
61
  var app = (0, _express.default)();
60
62
  var server = await (0, _serverInit.getServer)(app, options);
63
+ var serverChannel = (0, _getServerChannel.getServerChannel)(server);
61
64
  app.use((0, _compression.default)({
62
65
  level: 1
63
66
  }));
@@ -76,7 +79,7 @@ async function storybookDevServer(options) {
76
79
  var features = await options.presets.apply('features');
77
80
 
78
81
  if (features !== null && features !== void 0 && features.buildStoriesJson || features !== null && features !== void 0 && features.storyStoreV7) {
79
- await (0, _storiesJson.useStoriesJson)(router, options);
82
+ await (0, _storiesJson.useStoriesJson)(router, serverChannel, options);
80
83
  }
81
84
 
82
85
  (0, _middleware.getMiddleware)(options.configDir)(router);
@@ -107,7 +107,8 @@ exports.typescript = typescript;
107
107
 
108
108
  var features = async function (existing) {
109
109
  return _objectSpread(_objectSpread({}, existing), {}, {
110
- postcss: true
110
+ postcss: true,
111
+ emotionAlias: true
111
112
  });
112
113
  };
113
114
 
@@ -19,6 +19,8 @@ var _fsExtra = _interopRequireDefault(require("fs-extra"));
19
19
 
20
20
  var _globby = _interopRequireDefault(require("globby"));
21
21
 
22
+ var _slash = _interopRequireDefault(require("slash"));
23
+
22
24
  var _store = require("@storybook/store");
23
25
 
24
26
  var _nodeLogger = require("@storybook/node-logger");
@@ -74,9 +76,7 @@ class StoryIndexGenerator {
74
76
  // Find all matching paths for each specifier
75
77
  await Promise.all(this.specifiers.map(async function (specifier) {
76
78
  var pathToSubIndex = {};
77
-
78
- var fullGlob = _path.default.join(_this.options.workingDir, specifier.directory, specifier.files);
79
-
79
+ var fullGlob = (0, _slash.default)(_path.default.join(_this.options.workingDir, specifier.directory, specifier.files));
80
80
  var files = await (0, _globby.default)(fullGlob);
81
81
  files.forEach(function (absolutePath) {
82
82
  var ext = _path.default.extname(absolutePath);
@@ -113,10 +113,11 @@ class StoryIndexGenerator {
113
113
  async extractStories(specifier, absolutePath) {
114
114
  var relativePath = _path.default.relative(this.options.workingDir, absolutePath);
115
115
 
116
+ var fileStories = {};
117
+ var entry = this.storyIndexEntries.get(specifier);
118
+
116
119
  try {
117
- var entry = this.storyIndexEntries.get(specifier);
118
- var fileStories = {};
119
- var importPath = relativePath[0] === '.' ? relativePath : `./${relativePath}`;
120
+ var importPath = (0, _slash.default)(relativePath[0] === '.' ? relativePath : `./${relativePath}`);
120
121
  var defaultTitle = (0, _store.autoTitleFromSpecifier)(importPath, specifier);
121
122
  var csf = (await (0, _csfTools.readCsfOrMdx)(absolutePath, {
122
123
  defaultTitle: defaultTitle
@@ -132,13 +133,18 @@ class StoryIndexGenerator {
132
133
  importPath: importPath
133
134
  };
134
135
  });
135
- entry[absolutePath] = fileStories;
136
- return fileStories;
137
136
  } catch (err) {
138
- _nodeLogger.logger.warn(`🚨 Extraction error on ${relativePath}: ${err}`);
137
+ if (err.name === 'NoMetaError') {
138
+ _nodeLogger.logger.info(`💡 Skipping ${relativePath}: ${err}`);
139
+ } else {
140
+ _nodeLogger.logger.warn(`🚨 Extraction error on ${relativePath}: ${err}`);
139
141
 
140
- throw err;
142
+ throw err;
143
+ }
141
144
  }
145
+
146
+ entry[absolutePath] = fileStories;
147
+ return fileStories;
142
148
  }
143
149
 
144
150
  async sortStories(storiesList) {
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.StoryOne = void 0;
7
+
8
+ /* eslint-disable storybook/default-exports */
9
+ // no default export
10
+ // e.g. https://github.com/storybookjs/storybook/issues/16421
11
+ var StoryOne = {};
12
+ exports.StoryOne = StoryOne;
@@ -4,6 +4,7 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.copyAllStaticFiles = copyAllStaticFiles;
7
+ exports.copyAllStaticFilesRelativeToMain = copyAllStaticFilesRelativeToMain;
7
8
 
8
9
  require("core-js/modules/es.promise.js");
9
10
 
@@ -15,6 +16,8 @@ var _path = _interopRequireDefault(require("path"));
15
16
 
16
17
  var _nodeLogger = require("@storybook/node-logger");
17
18
 
19
+ var _coreCommon = require("@storybook/core-common");
20
+
18
21
  var _serverStatics = require("./server-statics");
19
22
 
20
23
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
@@ -50,4 +53,34 @@ async function copyAllStaticFiles(staticDirs, outputDir) {
50
53
  }
51
54
  }));
52
55
  }
56
+ }
57
+
58
+ async function copyAllStaticFilesRelativeToMain(staticDirs, outputDir, configDir) {
59
+ staticDirs.forEach(async function (dir) {
60
+ var staticDirAndTarget = typeof dir === 'string' ? dir : `${dir.from}:${dir.to}`;
61
+
62
+ var _await$parseStaticDir2 = await (0, _serverStatics.parseStaticDir)((0, _coreCommon.getDirectoryFromWorkingDir)({
63
+ configDir: configDir,
64
+ workingDir: process.cwd(),
65
+ directory: staticDirAndTarget
66
+ })),
67
+ from = _await$parseStaticDir2.staticPath,
68
+ to = _await$parseStaticDir2.targetEndpoint;
69
+
70
+ var targetPath = _path.default.join(outputDir, to);
71
+
72
+ var skipPaths = ['index.html', 'iframe.html'].map(function (f) {
73
+ return _path.default.join(targetPath, f);
74
+ });
75
+
76
+ _nodeLogger.logger.info((0, _chalk.default)`=> Copying static files: {cyan ${from}} at {cyan ${targetPath}}`);
77
+
78
+ await _fsExtra.default.copy(from, targetPath, {
79
+ dereference: true,
80
+ preserveTimestamps: true,
81
+ filter: function (_, dest) {
82
+ return !skipPaths.includes(dest);
83
+ }
84
+ });
85
+ });
53
86
  }
@@ -18,6 +18,8 @@ function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return
18
18
  function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
19
19
 
20
20
  async function getManagerBuilder(configDir) {
21
+ var _core$builder;
22
+
21
23
  var main = _path.default.resolve(configDir, 'main');
22
24
 
23
25
  var mainFile = (0, _coreCommon.getInterpretedFile)(main);
@@ -25,14 +27,15 @@ async function getManagerBuilder(configDir) {
25
27
  var _ref = mainFile ? (0, _coreCommon.serverRequire)(mainFile) : {
26
28
  core: null
27
29
  },
28
- core = _ref.core; // Builder can be any string including community builders like `storybook-builder-vite`.
30
+ core = _ref.core;
31
+
32
+ var builderName = typeof (core === null || core === void 0 ? void 0 : core.builder) === 'string' ? core.builder : core === null || core === void 0 ? void 0 : (_core$builder = core.builder) === null || _core$builder === void 0 ? void 0 : _core$builder.name; // Builder can be any string including community builders like `storybook-builder-vite`.
29
33
  // - For now, `webpack5` triggers `manager-webpack5`
30
34
  // - Everything else builds with `manager-webpack4`
31
35
  //
32
36
  // Unlike preview builders, manager building is not pluggable!
33
37
 
34
-
35
- var builderPackage = (core === null || core === void 0 ? void 0 : core.builder) === 'webpack5' ? require.resolve('@storybook/manager-webpack5', {
38
+ var builderPackage = builderName === 'webpack5' ? require.resolve('@storybook/manager-webpack5', {
36
39
  paths: [main]
37
40
  }) : '@storybook/manager-webpack4';
38
41
  var managerBuilder = await Promise.resolve(`${builderPackage}`).then(function (s) {
@@ -27,10 +27,19 @@ async function getPreviewBuilder(configDir) {
27
27
  },
28
28
  core = _ref.core;
29
29
 
30
- var builder = core === null || core === void 0 ? void 0 : core.builder;
31
- var builderPackage = builder ? require.resolve(['webpack4', 'webpack5'].includes(builder) ? `@storybook/builder-${builder}` : builder, {
32
- paths: [main]
33
- }) : require.resolve('@storybook/builder-webpack4');
30
+ var builderPackage;
31
+
32
+ if (core) {
33
+ var _core$builder;
34
+
35
+ var builderName = typeof core.builder === 'string' ? core.builder : (_core$builder = core.builder) === null || _core$builder === void 0 ? void 0 : _core$builder.name;
36
+ builderPackage = require.resolve(['webpack4', 'webpack5'].includes(builderName) ? `@storybook/builder-${builderName}` : builderName, {
37
+ paths: [main]
38
+ });
39
+ } else {
40
+ builderPackage = require.resolve('@storybook/builder-webpack4');
41
+ }
42
+
34
43
  var previewBuilder = await Promise.resolve(`${builderPackage}`).then(function (s) {
35
44
  return _interopRequireWildcard(require(s));
36
45
  });
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.getServerChannel = getServerChannel;
7
+ exports.ServerChannel = void 0;
8
+
9
+ var _ws = _interopRequireWildcard(require("ws"));
10
+
11
+ var _telejson = require("telejson");
12
+
13
+ function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
14
+
15
+ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
16
+
17
+ class ServerChannel {
18
+ constructor(server) {
19
+ var _this = this;
20
+
21
+ this.webSocketServer = void 0;
22
+ this.webSocketServer = new _ws.WebSocketServer({
23
+ noServer: true
24
+ });
25
+ server.on('upgrade', function (request, socket, head) {
26
+ if (request.url === '/storybook-server-channel') {
27
+ _this.webSocketServer.handleUpgrade(request, socket, head, function (ws) {
28
+ _this.webSocketServer.emit('connection', ws, request);
29
+ });
30
+ }
31
+ });
32
+ }
33
+
34
+ emit(type, args = []) {
35
+ var event = {
36
+ type: type,
37
+ args: args
38
+ };
39
+ var data = (0, _telejson.stringify)(event, {
40
+ maxDepth: 15,
41
+ allowFunction: true
42
+ });
43
+ Array.from(this.webSocketServer.clients).filter(function (c) {
44
+ return c.readyState === _ws.default.OPEN;
45
+ }).forEach(function (client) {
46
+ return client.send(data);
47
+ });
48
+ }
49
+
50
+ }
51
+
52
+ exports.ServerChannel = ServerChannel;
53
+
54
+ function getServerChannel(server) {
55
+ return new ServerChannel(server);
56
+ }
@@ -4,7 +4,7 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.getServerAddresses = getServerAddresses;
7
- exports.getServerPort = void 0;
7
+ exports.getServerChannelUrl = exports.getServerPort = void 0;
8
8
 
9
9
  var _ip = _interopRequireDefault(require("ip"));
10
10
 
@@ -29,4 +29,12 @@ var getServerPort = function (port) {
29
29
  });
30
30
  };
31
31
 
32
- exports.getServerPort = getServerPort;
32
+ exports.getServerPort = getServerPort;
33
+
34
+ var getServerChannelUrl = function (port, {
35
+ https: https
36
+ }) {
37
+ return `${https ? 'wss' : 'ws'}://localhost:${port}/storybook-server-channel`;
38
+ };
39
+
40
+ exports.getServerChannelUrl = getServerChannelUrl;
@@ -12,6 +12,8 @@ require("core-js/modules/es.promise.js");
12
12
 
13
13
  var _nodeLogger = require("@storybook/node-logger");
14
14
 
15
+ var _coreCommon = require("@storybook/core-common");
16
+
15
17
  var _chalk = _interopRequireDefault(require("chalk"));
16
18
 
17
19
  var _express = _interopRequireDefault(require("express"));
@@ -42,14 +44,45 @@ var defaultFavIcon = require.resolve('../public/favicon.ico');
42
44
 
43
45
  async function useStatics(router, options) {
44
46
  var hasCustomFavicon = false;
47
+ var staticDirs = await options.presets.apply('staticDirs');
48
+
49
+ if (staticDirs && options.staticDir) {
50
+ throw new Error((0, _tsDedent.default)`
51
+ Conflict when trying to read staticDirs:
52
+ * Storybook's configuration option: 'staticDirs'
53
+ * Storybook's CLI flag: '--staticDir' or '-s'
54
+
55
+ Choose one of them, but not both.
56
+ `);
57
+ }
58
+
59
+ if (staticDirs) {
60
+ staticDirs.forEach(async function (dir) {
61
+ var staticDirAndTarget = typeof dir === 'string' ? dir : `${dir.from}:${dir.to}`;
62
+
63
+ var _await$parseStaticDir = await parseStaticDir((0, _coreCommon.getDirectoryFromWorkingDir)({
64
+ configDir: options.configDir,
65
+ workingDir: process.cwd(),
66
+ directory: staticDirAndTarget
67
+ })),
68
+ from = _await$parseStaticDir.staticPath,
69
+ to = _await$parseStaticDir.targetEndpoint;
70
+
71
+ _nodeLogger.logger.info((0, _chalk.default)`=> Serving static files from {cyan ${from}} at {cyan ${to}}`);
72
+
73
+ router.use(to, _express.default.static(from, {
74
+ index: false
75
+ }));
76
+ });
77
+ }
45
78
 
46
79
  if (options.staticDir && options.staticDir.length > 0) {
47
80
  await Promise.all(options.staticDir.map(async function (dir) {
48
81
  try {
49
- var _await$parseStaticDir = await parseStaticDir(dir),
50
- staticDir = _await$parseStaticDir.staticDir,
51
- staticPath = _await$parseStaticDir.staticPath,
52
- targetEndpoint = _await$parseStaticDir.targetEndpoint;
82
+ var _await$parseStaticDir2 = await parseStaticDir(dir),
83
+ staticDir = _await$parseStaticDir2.staticDir,
84
+ staticPath = _await$parseStaticDir2.staticPath,
85
+ targetEndpoint = _await$parseStaticDir2.targetEndpoint;
53
86
 
54
87
  _nodeLogger.logger.info((0, _chalk.default)`=> Serving static files from {cyan ${staticDir}} at {cyan ${targetEndpoint}}`);
55
88
 
@@ -5,24 +5,26 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.extractStoriesJson = extractStoriesJson;
7
7
  exports.useStoriesJson = useStoriesJson;
8
+ exports.DEBOUNCE = void 0;
8
9
 
9
10
  require("core-js/modules/es.promise.js");
10
11
 
11
12
  var _fsExtra = _interopRequireDefault(require("fs-extra"));
12
13
 
13
- var _events = _interopRequireDefault(require("events"));
14
-
15
14
  var _coreCommon = require("@storybook/core-common");
16
15
 
16
+ var _coreEvents = _interopRequireDefault(require("@storybook/core-events"));
17
+
18
+ var _debounce = _interopRequireDefault(require("lodash/debounce"));
19
+
17
20
  var _StoryIndexGenerator = require("./StoryIndexGenerator");
18
21
 
19
22
  var _watchStorySpecifiers = require("./watch-story-specifiers");
20
23
 
21
- var _useEventsAsSse = require("./use-events-as-sse");
22
-
23
24
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
24
25
 
25
- var INVALIDATE = 'INVALIDATE';
26
+ var DEBOUNCE = 100;
27
+ exports.DEBOUNCE = DEBOUNCE;
26
28
 
27
29
  async function extractStoriesJson(outputFile, normalizedStories, options) {
28
30
  var generator = new _StoryIndexGenerator.StoryIndexGenerator(normalizedStories, options);
@@ -31,7 +33,7 @@ async function extractStoriesJson(outputFile, normalizedStories, options) {
31
33
  await _fsExtra.default.writeJson(outputFile, index);
32
34
  }
33
35
 
34
- async function useStoriesJson(router, options, workingDir = process.cwd()) {
36
+ async function useStoriesJson(router, serverChannel, options, workingDir = process.cwd()) {
35
37
  var normalizedStories = (0, _coreCommon.normalizeStories)(await options.presets.apply('stories'), {
36
38
  configDir: options.configDir,
37
39
  workingDir: workingDir
@@ -45,22 +47,26 @@ async function useStoriesJson(router, options, workingDir = process.cwd()) {
45
47
  // This is mainly for testing purposes.
46
48
 
47
49
  var started = false;
48
- var invalidationEmitter = new _events.default();
50
+ var maybeInvalidate = (0, _debounce.default)(function () {
51
+ return serverChannel.emit(_coreEvents.default.STORY_INDEX_INVALIDATED);
52
+ }, DEBOUNCE, {
53
+ leading: true
54
+ });
49
55
 
50
56
  async function ensureStarted() {
51
57
  if (started) return;
52
58
  started = true;
53
- (0, _watchStorySpecifiers.watchStorySpecifiers)(normalizedStories, function (specifier, path, removed) {
59
+ (0, _watchStorySpecifiers.watchStorySpecifiers)(normalizedStories, {
60
+ workingDir: workingDir
61
+ }, function (specifier, path, removed) {
54
62
  generator.invalidate(specifier, path, removed);
55
- invalidationEmitter.emit(INVALIDATE);
63
+ maybeInvalidate();
56
64
  });
57
65
  await generator.initialize();
58
66
  }
59
67
 
60
- var eventsAsSSE = (0, _useEventsAsSse.useEventsAsSSE)(invalidationEmitter, [INVALIDATE]);
61
68
  router.use('/stories.json', async function (req, res) {
62
69
  await ensureStarted();
63
- if (eventsAsSSE(req, res)) return;
64
70
 
65
71
  try {
66
72
  var index = await generator.getIndex();
@@ -5,11 +5,36 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.watchStorySpecifiers = watchStorySpecifiers;
7
7
 
8
+ require("core-js/modules/es.promise.js");
9
+
8
10
  var _watchpack = _interopRequireDefault(require("watchpack"));
9
11
 
12
+ var _slash = _interopRequireDefault(require("slash"));
13
+
14
+ var _fs = _interopRequireDefault(require("fs"));
15
+
16
+ var _path = _interopRequireDefault(require("path"));
17
+
18
+ var _globby = _interopRequireDefault(require("globby"));
19
+
10
20
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
21
 
12
- function watchStorySpecifiers(specifiers, onInvalidate) {
22
+ var isDirectory = function (directory) {
23
+ try {
24
+ return _fs.default.lstatSync(directory).isDirectory();
25
+ } catch (err) {
26
+ return false;
27
+ }
28
+ }; // Watchpack (and path.relative) passes paths either with no leading './' - e.g. `src/Foo.stories.js`,
29
+ // or with a leading `../` (etc), e.g. `../src/Foo.stories.js`.
30
+ // We want to deal in importPaths relative to the working dir, so we normalize
31
+
32
+
33
+ function toImportPath(relativePath) {
34
+ return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
35
+ }
36
+
37
+ function watchStorySpecifiers(specifiers, options, onInvalidate) {
13
38
  // See https://www.npmjs.com/package/watchpack for full options.
14
39
  // If you want less traffic, consider using aggregation with some interval
15
40
  var wp = new _watchpack.default({
@@ -23,21 +48,52 @@ function watchStorySpecifiers(specifiers, onInvalidate) {
23
48
  })
24
49
  });
25
50
 
26
- function onChangeOrRemove(watchpackPath, removed) {
51
+ async function onChangeOrRemove(watchpackPath, removed) {
27
52
  // Watchpack passes paths either with no leading './' - e.g. `src/Foo.stories.js`,
28
53
  // or with a leading `../` (etc), e.g. `../src/Foo.stories.js`.
29
54
  // We want to deal in importPaths relative to the working dir, or absolute paths.
30
- var importPath = watchpackPath.startsWith('.') ? watchpackPath : `./${watchpackPath}`;
31
- var specifier = specifiers.find(function (ns) {
55
+ var importPath = (0, _slash.default)(watchpackPath.startsWith('.') ? watchpackPath : `./${watchpackPath}`);
56
+ var matchingSpecifier = specifiers.find(function (ns) {
32
57
  return ns.importPathMatcher.exec(importPath);
33
58
  });
34
59
 
35
- if (specifier) {
36
- onInvalidate(specifier, importPath, removed);
60
+ if (matchingSpecifier) {
61
+ onInvalidate(matchingSpecifier, importPath, removed);
62
+ return;
63
+ } // When a directory is removed, watchpack will fire a removed event for each file also
64
+ // (so we don't need to do anything special).
65
+ // However, when a directory is added, it does not fire events for any files *within* the directory,
66
+ // so we need to scan within that directory for new files. It is tricky to use a glob for this,
67
+ // so we'll do something a bit more "dumb" for now
68
+
69
+
70
+ var absolutePath = _path.default.join(options.workingDir, importPath);
71
+
72
+ if (!removed && isDirectory(absolutePath)) {
73
+ await Promise.all(specifiers // We only receive events for files (incl. directories) that are *within* a specifier,
74
+ // so will match one (or more) specifiers with this simple `startsWith`
75
+ .filter(function (specifier) {
76
+ return importPath.startsWith(specifier.directory);
77
+ }).map(async function (specifier) {
78
+ // If `./path/to/dir` was added, check all files matching `./path/to/dir/**/*.stories.*`
79
+ // (where the last bit depends on `files`).
80
+ var dirGlob = _path.default.join(options.workingDir, importPath, '**', // files can be e.g. '**/foo/*/*.js' so we just want the last bit,
81
+ // because the directoru could already be within the files part (e.g. './x/foo/bar')
82
+ _path.default.basename(specifier.files));
83
+
84
+ var files = await (0, _globby.default)(dirGlob);
85
+ files.forEach(function (filePath) {
86
+ var fileImportPath = toImportPath(_path.default.relative(options.workingDir, filePath));
87
+
88
+ if (specifier.importPathMatcher.exec(fileImportPath)) {
89
+ onInvalidate(specifier, fileImportPath, removed);
90
+ }
91
+ });
92
+ }));
37
93
  }
38
94
  }
39
95
 
40
- wp.on('change', function (path, mtime, explanation) {
96
+ wp.on('change', async function (filePath, mtime, explanation) {
41
97
  // When a file is renamed (including being moved out of the watched dir)
42
98
  // we see first an event with explanation=rename and no mtime for the old name.
43
99
  // then an event with explanation=rename with an mtime for the new name.
@@ -45,10 +101,10 @@ function watchStorySpecifiers(specifiers, onInvalidate) {
45
101
  // but that seems dangerous (what if the contents changed?) and frankly not worth it
46
102
  // (at this stage at least)
47
103
  var removed = !mtime;
48
- onChangeOrRemove(path, removed);
104
+ await onChangeOrRemove(filePath, removed);
49
105
  });
50
- wp.on('remove', function (path, explanation) {
51
- onChangeOrRemove(path, true);
106
+ wp.on('remove', async function (filePath, explanation) {
107
+ await onChangeOrRemove(filePath, true);
52
108
  });
53
109
  return function () {
54
110
  return wp.close();
@@ -29,7 +29,7 @@ import { getReleaseNotesData, getReleaseNotesFailedState } from './utils/release
29
29
  import { outputStats } from './utils/output-stats';
30
30
  import { outputStartupInformation } from './utils/output-startup-information';
31
31
  import { updateCheck } from './utils/update-check';
32
- import { getServerPort } from './utils/server-address';
32
+ import { getServerPort, getServerChannelUrl } from './utils/server-address';
33
33
  import { getPreviewBuilder } from './utils/get-preview-builder';
34
34
  import { getManagerBuilder } from './utils/get-manager-builder';
35
35
  export async function buildDevStandalone(options) {
@@ -70,6 +70,7 @@ export async function buildDevStandalone(options) {
70
70
  options.configType = 'DEVELOPMENT';
71
71
  options.configDir = path.resolve(options.configDir);
72
72
  options.outputDir = options.smokeTest ? resolvePathInStorybookCache('public') : path.resolve(options.outputDir || resolvePathInStorybookCache('public'));
73
+ options.serverChannelUrl = getServerChannelUrl(port, options);
73
74
  /* eslint-enable no-param-reassign */
74
75
 
75
76
  var previewBuilder = await getPreviewBuilder(options.configDir);