@storybook/builder-vite 0.2.1 → 7.0.0-alpha.26

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 (178) hide show
  1. package/dist/cjs/build.js +34 -0
  2. package/dist/cjs/code-generator-plugin.js +177 -0
  3. package/dist/cjs/codegen-entries.js +54 -0
  4. package/dist/{codegen-iframe-script.js → cjs/codegen-iframe-script.js} +36 -20
  5. package/dist/cjs/codegen-importfn-script.js +68 -0
  6. package/dist/cjs/codegen-modern-iframe-script.js +84 -0
  7. package/dist/{codegen-set-addon-channel.js → cjs/codegen-set-addon-channel.js} +10 -8
  8. package/dist/cjs/declarations/extract-stories.d.js +1 -0
  9. package/dist/cjs/declarations/svetle-stories-loader.d.js +1 -0
  10. package/dist/cjs/envs.js +42 -0
  11. package/dist/cjs/index.js +88 -0
  12. package/dist/cjs/inject-export-order-plugin.js +48 -0
  13. package/dist/cjs/list-stories.js +29 -0
  14. package/dist/cjs/optimizeDeps.js +45 -0
  15. package/dist/cjs/plugins/docgen-handlers/actualNameHandler.js +49 -0
  16. package/dist/cjs/plugins/mdx-plugin.js +91 -0
  17. package/dist/{plugins → cjs/plugins}/no-fouc.js +20 -16
  18. package/dist/cjs/plugins/react-docgen.js +81 -0
  19. package/dist/cjs/source-loader-plugin.js +119 -0
  20. package/dist/cjs/transform-iframe-html.js +31 -0
  21. package/dist/cjs/types/envs-raw.type.js +1 -0
  22. package/dist/cjs/types/extended-options.type.js +5 -0
  23. package/dist/cjs/types/index.js +31 -0
  24. package/dist/cjs/types/react-docgen.d.js +1 -0
  25. package/dist/cjs/utils/transform-abs-path.js +21 -0
  26. package/dist/cjs/virtual-file-names.js +14 -0
  27. package/dist/cjs/vite-config.js +96 -0
  28. package/dist/cjs/vite-server.js +43 -0
  29. package/dist/esm/build.js +24 -0
  30. package/dist/esm/code-generator-plugin.js +153 -0
  31. package/dist/esm/codegen-entries.js +40 -0
  32. package/dist/esm/codegen-iframe-script.js +114 -0
  33. package/dist/esm/codegen-importfn-script.js +54 -0
  34. package/dist/esm/codegen-modern-iframe-script.js +73 -0
  35. package/dist/esm/codegen-set-addon-channel.js +18 -0
  36. package/dist/{mdx-plugin.d.ts → esm/declarations/extract-stories.d.js} +0 -0
  37. package/dist/esm/declarations/svetle-stories-loader.d.js +0 -0
  38. package/dist/esm/envs.js +31 -0
  39. package/dist/esm/index.js +68 -0
  40. package/dist/esm/inject-export-order-plugin.js +35 -0
  41. package/dist/esm/list-stories.js +15 -0
  42. package/dist/esm/optimizeDeps.js +31 -0
  43. package/dist/esm/plugins/docgen-handlers/actualNameHandler.js +41 -0
  44. package/dist/esm/plugins/mdx-plugin.js +78 -0
  45. package/dist/esm/plugins/no-fouc.js +48 -0
  46. package/dist/esm/plugins/react-docgen.js +63 -0
  47. package/dist/esm/source-loader-plugin.js +108 -0
  48. package/dist/esm/transform-iframe-html.js +23 -0
  49. package/dist/esm/types/envs-raw.type.js +0 -0
  50. package/dist/esm/types/extended-options.type.js +1 -0
  51. package/dist/esm/types/index.js +2 -0
  52. package/dist/esm/types/react-docgen.d.js +0 -0
  53. package/dist/esm/utils/transform-abs-path.js +10 -0
  54. package/dist/esm/virtual-file-names.js +4 -0
  55. package/dist/esm/vite-config.js +68 -0
  56. package/dist/esm/vite-server.js +32 -0
  57. package/dist/{build.d.ts → types/build.d.ts} +0 -0
  58. package/dist/{code-generator-plugin.d.ts → types/code-generator-plugin.d.ts} +0 -0
  59. package/dist/{codegen-entries.d.ts → types/codegen-entries.d.ts} +0 -0
  60. package/dist/{codegen-iframe-script.d.ts → types/codegen-iframe-script.d.ts} +0 -0
  61. package/dist/{codegen-importfn-script.d.ts → types/codegen-importfn-script.d.ts} +0 -0
  62. package/dist/{codegen-modern-iframe-script.d.ts → types/codegen-modern-iframe-script.d.ts} +0 -0
  63. package/dist/{codegen-set-addon-channel.d.ts → types/codegen-set-addon-channel.d.ts} +0 -0
  64. package/dist/{envs.d.ts → types/envs.d.ts} +1 -1
  65. package/dist/types/index.d.ts +13 -2
  66. package/dist/{inject-export-order-plugin.d.ts → types/inject-export-order-plugin.d.ts} +0 -0
  67. package/dist/{list-stories.d.ts → types/list-stories.d.ts} +0 -0
  68. package/dist/{optimizeDeps.d.ts → types/optimizeDeps.d.ts} +0 -0
  69. package/dist/{plugins → types/plugins}/docgen-handlers/actualNameHandler.d.ts +0 -0
  70. package/dist/{plugins → types/plugins}/mdx-plugin.d.ts +1 -1
  71. package/dist/{plugins → types/plugins}/no-fouc.d.ts +0 -0
  72. package/dist/{plugins → types/plugins}/react-docgen.d.ts +0 -0
  73. package/dist/{source-loader-plugin.d.ts → types/source-loader-plugin.d.ts} +0 -0
  74. package/dist/{transform-iframe-html.d.ts → types/transform-iframe-html.d.ts} +0 -0
  75. package/dist/types/{envs-raw.type.d.ts → types/envs-raw.type.d.ts} +0 -0
  76. package/dist/types/{extended-options.type.d.ts → types/extended-options.type.d.ts} +1 -0
  77. package/{types/index.ts → dist/types/types/index.d.ts} +0 -0
  78. package/dist/{utils → types/utils}/transform-abs-path.d.ts +0 -0
  79. package/dist/{virtual-file-names.d.ts → types/virtual-file-names.d.ts} +0 -0
  80. package/dist/{vite-config.d.ts → types/vite-config.d.ts} +0 -0
  81. package/dist/{vite-server.d.ts → types/vite-server.d.ts} +0 -0
  82. package/input/iframe.html +2 -2
  83. package/package.json +28 -19
  84. package/{build.ts → src/build.ts} +0 -0
  85. package/{code-generator-plugin.ts → src/code-generator-plugin.ts} +31 -14
  86. package/{codegen-entries.ts → src/codegen-entries.ts} +0 -0
  87. package/{codegen-iframe-script.ts → src/codegen-iframe-script.ts} +14 -4
  88. package/{codegen-importfn-script.ts → src/codegen-importfn-script.ts} +0 -0
  89. package/{codegen-modern-iframe-script.ts → src/codegen-modern-iframe-script.ts} +12 -5
  90. package/{codegen-set-addon-channel.ts → src/codegen-set-addon-channel.ts} +2 -2
  91. package/{declarations → src/declarations}/extract-stories.d.ts +0 -0
  92. package/{declarations → src/declarations}/svetle-stories-loader.d.ts +0 -0
  93. package/{envs.ts → src/envs.ts} +1 -1
  94. package/{index.ts → src/index.ts} +30 -15
  95. package/{inject-export-order-plugin.ts → src/inject-export-order-plugin.ts} +7 -4
  96. package/{list-stories.ts → src/list-stories.ts} +0 -0
  97. package/{optimizeDeps.ts → src/optimizeDeps.ts} +0 -0
  98. package/{plugins → src/plugins}/docgen-handlers/actualNameHandler.ts +8 -3
  99. package/{plugins → src/plugins}/mdx-plugin.ts +21 -14
  100. package/{plugins → src/plugins}/no-fouc.ts +1 -3
  101. package/{plugins → src/plugins}/react-docgen.ts +7 -4
  102. package/{source-loader-plugin.ts → src/source-loader-plugin.ts} +9 -2
  103. package/{transform-iframe-html.ts → src/transform-iframe-html.ts} +0 -0
  104. package/{types → src/types}/envs-raw.type.ts +0 -0
  105. package/{types → src/types}/extended-options.type.ts +2 -0
  106. package/src/types/index.ts +2 -0
  107. package/{types → src/types}/react-docgen.d.ts +0 -0
  108. package/{utils → src/utils}/transform-abs-path.ts +0 -0
  109. package/{virtual-file-names.ts → src/virtual-file-names.ts} +0 -0
  110. package/src/vite-config.ts +83 -0
  111. package/{vite-server.ts → src/vite-server.ts} +2 -3
  112. package/tsconfig.json +5 -4
  113. package/dist/build.js +0 -30
  114. package/dist/build.js.map +0 -1
  115. package/dist/code-generator-plugin.js +0 -156
  116. package/dist/code-generator-plugin.js.map +0 -1
  117. package/dist/codegen-entries.js +0 -42
  118. package/dist/codegen-entries.js.map +0 -1
  119. package/dist/codegen-iframe-script.js.map +0 -1
  120. package/dist/codegen-importfn-script.js +0 -75
  121. package/dist/codegen-importfn-script.js.map +0 -1
  122. package/dist/codegen-modern-iframe-script.js +0 -67
  123. package/dist/codegen-modern-iframe-script.js.map +0 -1
  124. package/dist/codegen-set-addon-channel.js.map +0 -1
  125. package/dist/envs.js +0 -43
  126. package/dist/envs.js.map +0 -1
  127. package/dist/index.d.ts +0 -12
  128. package/dist/index.js +0 -84
  129. package/dist/index.js.map +0 -1
  130. package/dist/inject-export-order-plugin.js +0 -34
  131. package/dist/inject-export-order-plugin.js.map +0 -1
  132. package/dist/list-stories.js +0 -40
  133. package/dist/list-stories.js.map +0 -1
  134. package/dist/mdx-plugin.js +0 -2
  135. package/dist/mdx-plugin.js.map +0 -1
  136. package/dist/mock-core-js.d.ts +0 -5
  137. package/dist/mock-core-js.js +0 -22
  138. package/dist/mock-core-js.js.map +0 -1
  139. package/dist/optimizeDeps.js +0 -142
  140. package/dist/optimizeDeps.js.map +0 -1
  141. package/dist/plugins/docgen-handlers/actualNameHandler.js +0 -43
  142. package/dist/plugins/docgen-handlers/actualNameHandler.js.map +0 -1
  143. package/dist/plugins/mdx-plugin.js +0 -87
  144. package/dist/plugins/mdx-plugin.js.map +0 -1
  145. package/dist/plugins/no-fouc.js.map +0 -1
  146. package/dist/plugins/react-docgen.js +0 -52
  147. package/dist/plugins/react-docgen.js.map +0 -1
  148. package/dist/plugins/svelte-docgen.d.ts +0 -2
  149. package/dist/plugins/svelte-docgen.js +0 -83
  150. package/dist/plugins/svelte-docgen.js.map +0 -1
  151. package/dist/plugins/vue-docgen.d.ts +0 -2
  152. package/dist/plugins/vue-docgen.js +0 -27
  153. package/dist/plugins/vue-docgen.js.map +0 -1
  154. package/dist/source-loader-plugin.js +0 -92
  155. package/dist/source-loader-plugin.js.map +0 -1
  156. package/dist/svelte/csf-plugin.d.ts +0 -9
  157. package/dist/svelte/csf-plugin.js +0 -75
  158. package/dist/svelte/csf-plugin.js.map +0 -1
  159. package/dist/transform-iframe-html.js +0 -32
  160. package/dist/transform-iframe-html.js.map +0 -1
  161. package/dist/types/envs-raw.type.js +0 -3
  162. package/dist/types/envs-raw.type.js.map +0 -1
  163. package/dist/types/extended-options.type.js +0 -3
  164. package/dist/types/extended-options.type.js.map +0 -1
  165. package/dist/types/index.js +0 -19
  166. package/dist/types/index.js.map +0 -1
  167. package/dist/utils/transform-abs-path.js +0 -18
  168. package/dist/utils/transform-abs-path.js.map +0 -1
  169. package/dist/virtual-file-names.js +0 -8
  170. package/dist/virtual-file-names.js.map +0 -1
  171. package/dist/vite-config.js +0 -196
  172. package/dist/vite-config.js.map +0 -1
  173. package/dist/vite-server.js +0 -38
  174. package/dist/vite-server.js.map +0 -1
  175. package/plugins/svelte-docgen.ts +0 -97
  176. package/plugins/vue-docgen.ts +0 -23
  177. package/svelte/csf-plugin.ts +0 -52
  178. package/vite-config.ts +0 -199
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.build = build;
7
+
8
+ var _vite = require("vite");
9
+
10
+ var _envs = require("./envs");
11
+
12
+ var _viteConfig = require("./vite-config");
13
+
14
+ async function build(options) {
15
+ const {
16
+ presets
17
+ } = options;
18
+ const baseConfig = await (0, _viteConfig.commonConfig)(options, 'build');
19
+ const config = Object.assign({}, baseConfig, {
20
+ build: {
21
+ outDir: options.outputDir,
22
+ emptyOutDir: false,
23
+ // do not clean before running Vite build - Storybook has already added assets in there!
24
+ sourcemap: true
25
+ }
26
+ });
27
+ const finalConfig = await presets.apply('viteFinal', config, options);
28
+ const envsRaw = await presets.apply('env'); // Stringify env variables after getting `envPrefix` from the final config
29
+
30
+ const envs = (0, _envs.stringifyProcessEnvs)(envsRaw, finalConfig.envPrefix); // Update `define`
31
+
32
+ finalConfig.define = Object.assign({}, finalConfig.define, envs);
33
+ await (0, _vite.build)(finalConfig);
34
+ }
@@ -0,0 +1,177 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.codeGeneratorPlugin = codeGeneratorPlugin;
7
+
8
+ var fs = _interopRequireWildcard(require("fs"));
9
+
10
+ var path = _interopRequireWildcard(require("path"));
11
+
12
+ var _vite = require("vite");
13
+
14
+ var _transformIframeHtml = require("./transform-iframe-html");
15
+
16
+ var _codegenIframeScript = require("./codegen-iframe-script");
17
+
18
+ var _codegenModernIframeScript = require("./codegen-modern-iframe-script");
19
+
20
+ var _codegenImportfnScript = require("./codegen-importfn-script");
21
+
22
+ var _codegenEntries = require("./codegen-entries");
23
+
24
+ var _codegenSetAddonChannel = require("./codegen-set-addon-channel");
25
+
26
+ var _virtualFileNames = require("./virtual-file-names");
27
+
28
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
29
+
30
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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; }
31
+
32
+ /* eslint-disable no-param-reassign */
33
+ function codeGeneratorPlugin(options) {
34
+ const iframePath = path.resolve(__dirname, '../..', 'input', 'iframe.html');
35
+ let iframeId; // noinspection JSUnusedGlobalSymbols
36
+
37
+ return {
38
+ name: 'storybook-vite-code-generator-plugin',
39
+ enforce: 'pre',
40
+
41
+ configureServer(server) {
42
+ // invalidate the whole vite-app.js script on every file change.
43
+ // (this might be a little too aggressive?)
44
+ server.watcher.on('change', () => {
45
+ const appModule = server.moduleGraph.getModuleById(_virtualFileNames.virtualFileId);
46
+
47
+ if (appModule) {
48
+ server.moduleGraph.invalidateModule(appModule);
49
+ }
50
+
51
+ const storiesModule = server.moduleGraph.getModuleById(_virtualFileNames.virtualStoriesFile);
52
+
53
+ if (storiesModule) {
54
+ server.moduleGraph.invalidateModule(storiesModule);
55
+ }
56
+ }); // Adding new story files is not covered by the change event above. So we need to detect this and trigger
57
+ // HMR to update the importFn.
58
+
59
+ server.watcher.on('add', path => {
60
+ // TODO maybe use the stories declaration in main
61
+ if (/\.stories\.([tj])sx?$/.test(path) || /\.(story|stories).mdx$/.test(path)) {
62
+ // We need to emit a change event to trigger HMR
63
+ server.watcher.emit('change', _virtualFileNames.virtualStoriesFile);
64
+ }
65
+ });
66
+ },
67
+
68
+ config(config, {
69
+ command
70
+ }) {
71
+ // If we are building the static distribution, add iframe.html as an entry.
72
+ // In development mode, it's not an entry - instead, we use an express middleware
73
+ // to serve iframe.html. The reason is that Vite's dev server (at the time of writing)
74
+ // does not support virtual files as entry points.
75
+ if (command === 'build') {
76
+ if (!config.build) {
77
+ config.build = {};
78
+ }
79
+
80
+ config.build.rollupOptions = Object.assign({}, config.build.rollupOptions, {
81
+ input: iframePath
82
+ });
83
+ } // Detect if react 18 is installed. If not, alias it to a virtual placeholder file.
84
+
85
+
86
+ try {
87
+ require.resolve('react-dom/client', {
88
+ paths: [config.root || process.cwd()]
89
+ });
90
+ } catch (e) {
91
+ if (isNodeError(e) && e.code === 'MODULE_NOT_FOUND') {
92
+ config.resolve = (0, _vite.mergeConfig)(config.resolve ?? {}, {
93
+ alias: {
94
+ 'react-dom/client': path.resolve(__dirname, '../..', 'input', 'react-dom-client-placeholder.js')
95
+ }
96
+ });
97
+ }
98
+ }
99
+ },
100
+
101
+ configResolved(config) {
102
+ iframeId = `${config.root}/iframe.html`;
103
+ },
104
+
105
+ resolveId(source) {
106
+ if (source === _virtualFileNames.virtualFileId) {
107
+ return _virtualFileNames.virtualFileId;
108
+ }
109
+
110
+ if (source === iframePath) {
111
+ return iframeId;
112
+ }
113
+
114
+ if (source === _virtualFileNames.virtualStoriesFile) {
115
+ return _virtualFileNames.virtualStoriesFile;
116
+ }
117
+
118
+ if (source === _virtualFileNames.virtualPreviewFile) {
119
+ return _virtualFileNames.virtualPreviewFile;
120
+ }
121
+
122
+ if (source === _virtualFileNames.virtualAddonSetupFile) {
123
+ return _virtualFileNames.virtualAddonSetupFile;
124
+ }
125
+
126
+ return undefined;
127
+ },
128
+
129
+ async load(id) {
130
+ var _options$features;
131
+
132
+ const storyStoreV7 = (_options$features = options.features) === null || _options$features === void 0 ? void 0 : _options$features.storyStoreV7;
133
+
134
+ if (id === _virtualFileNames.virtualStoriesFile) {
135
+ if (storyStoreV7) {
136
+ return (0, _codegenImportfnScript.generateImportFnScriptCode)(options);
137
+ }
138
+
139
+ return (0, _codegenEntries.generateVirtualStoryEntryCode)(options);
140
+ }
141
+
142
+ if (id === _virtualFileNames.virtualAddonSetupFile) {
143
+ return (0, _codegenSetAddonChannel.generateAddonSetupCode)();
144
+ }
145
+
146
+ if (id === _virtualFileNames.virtualPreviewFile && !storyStoreV7) {
147
+ return (0, _codegenEntries.generatePreviewEntryCode)(options);
148
+ }
149
+
150
+ if (id === _virtualFileNames.virtualFileId) {
151
+ if (storyStoreV7) {
152
+ return (0, _codegenModernIframeScript.generateModernIframeScriptCode)(options);
153
+ }
154
+
155
+ return (0, _codegenIframeScript.generateIframeScriptCode)(options);
156
+ }
157
+
158
+ if (id === iframeId) {
159
+ return fs.readFileSync(path.resolve(__dirname, '../..', 'input', 'iframe.html'), 'utf-8');
160
+ }
161
+
162
+ return undefined;
163
+ },
164
+
165
+ async transformIndexHtml(html, ctx) {
166
+ if (ctx.path !== '/iframe.html') {
167
+ return undefined;
168
+ }
169
+
170
+ return (0, _transformIframeHtml.transformIframeHtml)(html, options);
171
+ }
172
+
173
+ };
174
+ } // Refines an error received from 'catch' to be a NodeJS exception
175
+
176
+
177
+ const isNodeError = error => error instanceof Error;
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.generatePreviewEntryCode = generatePreviewEntryCode;
7
+ exports.generateVirtualStoryEntryCode = generateVirtualStoryEntryCode;
8
+
9
+ var _coreCommon = require("@storybook/core-common");
10
+
11
+ var _slash = _interopRequireDefault(require("slash"));
12
+
13
+ var _vite = require("vite");
14
+
15
+ var _listStories = require("./list-stories");
16
+
17
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18
+
19
+ const absoluteFilesToImport = (files, name) => files.map((el, i) => `import ${name ? `* as ${name}_${i} from ` : ''}'/@fs/${(0, _vite.normalizePath)(el)}'`).join('\n');
20
+
21
+ async function generateVirtualStoryEntryCode(options) {
22
+ const storyEntries = await (0, _listStories.listStories)(options);
23
+ const resolveMap = storyEntries.reduce((prev, entry) => Object.assign({}, prev, {
24
+ [entry]: entry.replace((0, _slash.default)(process.cwd()), '.')
25
+ }), {});
26
+ const modules = storyEntries.map((entry, i) => `${JSON.stringify(entry)}: story_${i}`).join(',');
27
+ return `
28
+ ${absoluteFilesToImport(storyEntries, 'story')}
29
+
30
+ function loadable(key) {
31
+ return {${modules}}[key];
32
+ }
33
+
34
+ Object.assign(loadable, {
35
+ keys: () => (${JSON.stringify(Object.keys(resolveMap))}),
36
+ resolve: (key) => (${JSON.stringify(resolveMap)}[key])
37
+ });
38
+
39
+ export function configStories(configure) {
40
+ configure(loadable, { hot: import.meta.hot }, false);
41
+ }
42
+ `.trim();
43
+ }
44
+
45
+ async function generatePreviewEntryCode({
46
+ configDir
47
+ }) {
48
+ const previewFile = (0, _coreCommon.loadPreviewOrConfigFile)({
49
+ configDir
50
+ });
51
+ if (!previewFile) return '';
52
+ return `import * as preview from '${(0, _slash.default)(previewFile)}';
53
+ export default preview;`;
54
+ }
@@ -1,19 +1,37 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.generateIframeScriptCode = void 0;
4
- const virtual_file_names_1 = require("./virtual-file-names");
5
- const transform_abs_path_1 = require("./utils/transform-abs-path");
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.generateIframeScriptCode = generateIframeScriptCode;
7
+
8
+ var _path = require("path");
9
+
10
+ var _virtualFileNames = require("./virtual-file-names");
11
+
12
+ var _transformAbsPath = require("./utils/transform-abs-path");
13
+
6
14
  async function generateIframeScriptCode(options) {
7
- const { presets, frameworkPath, framework } = options;
8
- const frameworkImportPath = frameworkPath || `@storybook/${framework}`;
9
- const presetEntries = await presets.apply('config', [], options);
10
- const configEntries = [...presetEntries].filter(Boolean);
11
- const absoluteFilesToImport = (files, name) => files.map((el, i) => `import ${name ? `* as ${name}_${i} from ` : ''}'${(0, transform_abs_path_1.transformAbsPath)(el)}'`).join('\n');
12
- const importArray = (name, length) => new Array(length).fill(0).map((_, i) => `${name}_${i}`);
13
- // noinspection UnnecessaryLocalVariableJS
14
- /** @todo Inline variable and remove `noinspection` */
15
- // language=JavaScript
16
- const code = `
15
+ const {
16
+ presets,
17
+ frameworkPath,
18
+ framework
19
+ } = options;
20
+ const frameworkImportPath = frameworkPath || `@storybook/${framework}`;
21
+ const presetEntries = await presets.apply('config', [], options);
22
+ const previewEntries = await presets.apply('previewEntries', [], options);
23
+ const absolutePreviewEntries = previewEntries.map(entry => (0, _path.isAbsolute)(entry) ? entry : (0, _path.resolve)(entry));
24
+ const configEntries = [...presetEntries, ...absolutePreviewEntries].filter(Boolean);
25
+
26
+ const absoluteFilesToImport = (files, name) => files.map((el, i) => `import ${name ? `* as ${name}_${i} from ` : ''}'${(0, _transformAbsPath.transformAbsPath)(el)}'`).join('\n');
27
+
28
+ const importArray = (name, length) => new Array(length).fill(0).map((_, i) => `${name}_${i}`); // noinspection UnnecessaryLocalVariableJS
29
+
30
+ /** @todo Inline variable and remove `noinspection` */
31
+ // language=JavaScript
32
+
33
+
34
+ const code = `
17
35
  // Ensure that the client API is initialized by the framework before any other iframe code
18
36
  // is loaded. That way our client-apis can assume the existence of the API+store
19
37
  import { configure } from '${frameworkImportPath}';
@@ -21,8 +39,8 @@ async function generateIframeScriptCode(options) {
21
39
  import * as clientApi from "@storybook/client-api";
22
40
  import { logger } from '@storybook/client-logger';
23
41
  ${absoluteFilesToImport(configEntries, 'config')}
24
- import * as preview from '${virtual_file_names_1.virtualPreviewFile}';
25
- import { configStories } from '${virtual_file_names_1.virtualStoriesFile}';
42
+ import * as preview from '${_virtualFileNames.virtualPreviewFile}';
43
+ import { configStories } from '${_virtualFileNames.virtualStoriesFile}';
26
44
 
27
45
  const {
28
46
  addDecorator,
@@ -102,7 +120,5 @@ async function generateIframeScriptCode(options) {
102
120
 
103
121
  configStories(configure);
104
122
  `.trim();
105
- return code;
106
- }
107
- exports.generateIframeScriptCode = generateIframeScriptCode;
108
- //# sourceMappingURL=codegen-iframe-script.js.map
123
+ return code;
124
+ }
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.generateImportFnScriptCode = generateImportFnScriptCode;
7
+
8
+ var path = _interopRequireWildcard(require("path"));
9
+
10
+ var _vite = require("vite");
11
+
12
+ var _nodeLogger = require("@storybook/node-logger");
13
+
14
+ var _listStories = require("./list-stories");
15
+
16
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
17
+
18
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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
+
20
+ /**
21
+ * This file is largely based on https://github.com/storybookjs/storybook/blob/d1195cbd0c61687f1720fefdb772e2f490a46584/lib/core-common/src/utils/to-importFn.ts
22
+ */
23
+
24
+ /**
25
+ * Paths get passed either with no leading './' - e.g. `src/Foo.stories.js`,
26
+ * or with a leading `../` (etc), e.g. `../src/Foo.stories.js`.
27
+ * We want to deal in importPaths relative to the working dir, so we normalize
28
+ */
29
+ function toImportPath(relativePath) {
30
+ return relativePath.startsWith('../') ? relativePath : `./${relativePath}`;
31
+ }
32
+ /**
33
+ * This function takes an array of stories and creates a mapping between the stories' relative paths
34
+ * to the working directory and their dynamic imports. The import is done in an asynchronous function
35
+ * to delay loading. It then creates a function, `importFn(path)`, which resolves a path to an import
36
+ * function and this is called by Storybook to fetch a story dynamically when needed.
37
+ * @param stories An array of absolute story paths.
38
+ */
39
+
40
+
41
+ async function toImportFn(stories) {
42
+ const objectEntries = stories.map(file => {
43
+ const ext = path.extname(file);
44
+ const relativePath = (0, _vite.normalizePath)(path.relative(process.cwd(), file));
45
+
46
+ if (!['.js', '.jsx', '.ts', '.tsx', '.mdx'].includes(ext)) {
47
+ _nodeLogger.logger.warn(`Cannot process ${ext} file with storyStoreV7: ${relativePath}`);
48
+ }
49
+
50
+ return ` '${toImportPath(relativePath)}': async () => import('/@fs/${file}')`;
51
+ });
52
+ return `
53
+ const importers = {
54
+ ${objectEntries.join(',\n')}
55
+ };
56
+
57
+ export async function importFn(path) {
58
+ return importers[path]();
59
+ }
60
+ `;
61
+ }
62
+
63
+ async function generateImportFnScriptCode(options) {
64
+ // First we need to get an array of stories and their absolute paths.
65
+ const stories = await (0, _listStories.listStories)(options); // We can then call toImportFn to create a function that can be used to load each story dynamically.
66
+
67
+ return (await toImportFn(stories)).trim();
68
+ }
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.generateModernIframeScriptCode = generateModernIframeScriptCode;
7
+
8
+ var _path = require("path");
9
+
10
+ var _coreCommon = require("@storybook/core-common");
11
+
12
+ var _virtualFileNames = require("./virtual-file-names");
13
+
14
+ var _transformAbsPath = require("./utils/transform-abs-path");
15
+
16
+ async function generateModernIframeScriptCode(options) {
17
+ const {
18
+ presets,
19
+ configDir,
20
+ framework
21
+ } = options;
22
+ const previewOrConfigFile = (0, _coreCommon.loadPreviewOrConfigFile)({
23
+ configDir
24
+ });
25
+ const presetEntries = await presets.apply('config', [], options);
26
+ const previewEntries = await presets.apply('previewEntries', [], options);
27
+ const absolutePreviewEntries = previewEntries.map(entry => (0, _path.isAbsolute)(entry) ? entry : (0, _path.resolve)(entry));
28
+ const configEntries = [...presetEntries, ...absolutePreviewEntries, previewOrConfigFile].filter(Boolean).map(configEntry => (0, _transformAbsPath.transformAbsPath)(configEntry));
29
+
30
+ const generateHMRHandler = framework => {
31
+ // Web components are not compatible with HMR, so disable HMR, reload page instead.
32
+ if (framework === 'web-components') {
33
+ return `
34
+ if (import.meta.hot) {
35
+ import.meta.hot.decline();
36
+ }`.trim();
37
+ }
38
+
39
+ return `
40
+ if (import.meta.hot) {
41
+ import.meta.hot.accept('${_virtualFileNames.virtualStoriesFile}', (newModule) => {
42
+ // importFn has changed so we need to patch the new one in
43
+ preview.onStoriesChanged({ importFn: newModule.importFn });
44
+ });
45
+
46
+ import.meta.hot.accept(${JSON.stringify(configEntries)}, ([...newConfigEntries]) => {
47
+ const newGetProjectAnnotations = () => composeConfigs(newConfigEntries);
48
+
49
+ // getProjectAnnotations has changed so we need to patch the new one in
50
+ preview.onGetProjectAnnotationsChanged({ getProjectAnnotations: newGetProjectAnnotations });
51
+ });
52
+ }`.trim();
53
+ };
54
+ /**
55
+ * This code is largely taken from https://github.com/storybookjs/storybook/blob/d1195cbd0c61687f1720fefdb772e2f490a46584/lib/builder-webpack4/src/preview/virtualModuleModernEntry.js.handlebars
56
+ * Some small tweaks were made to `getProjectAnnotations` (since `import()` needs to be resolved asynchronously)
57
+ * and the HMR implementation has been tweaked to work with Vite.
58
+ * @todo Inline variable and remove `noinspection`
59
+ */
60
+
61
+
62
+ const code = `
63
+ import { composeConfigs, PreviewWeb } from '@storybook/preview-web';
64
+ import { ClientApi } from '@storybook/client-api';
65
+ import '${_virtualFileNames.virtualAddonSetupFile}';
66
+ import { importFn } from '${_virtualFileNames.virtualStoriesFile}';
67
+
68
+ const getProjectAnnotations = async () => {
69
+ const configs = await Promise.all([${configEntries.map(configEntry => `import('${configEntry}')`).join(',\n')}])
70
+ return composeConfigs(configs);
71
+ }
72
+
73
+ const preview = new PreviewWeb();
74
+
75
+ window.__STORYBOOK_PREVIEW__ = preview;
76
+ window.__STORYBOOK_STORY_STORE__ = preview.storyStore;
77
+ window.__STORYBOOK_CLIENT_API__ = new ClientApi({ storyStore: preview.storyStore });
78
+
79
+ preview.initialize({ importFn, getProjectAnnotations });
80
+
81
+ ${generateHMRHandler(framework)};
82
+ `.trim();
83
+ return code;
84
+ }
@@ -1,10 +1,14 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.generateAddonSetupCode = void 0;
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.generateAddonSetupCode = generateAddonSetupCode;
7
+
4
8
  function generateAddonSetupCode() {
5
- return `
6
- import createPostMessageChannel from '@storybook/channel-postmessage';
7
- import createWebSocketChannel from '@storybook/channel-websocket';
9
+ return `
10
+ import { createChannel as createPostMessageChannel } from '@storybook/channel-postmessage';
11
+ import { createChannel as createWebSocketChannel } from '@storybook/channel-websocket';
8
12
  import { addons } from '@storybook/addons';
9
13
 
10
14
  const channel = createPostMessageChannel({ page: 'preview' });
@@ -18,6 +22,4 @@ function generateAddonSetupCode() {
18
22
  window.__STORYBOOK_SERVER_CHANNEL__ = serverChannel;
19
23
  }
20
24
  `.trim();
21
- }
22
- exports.generateAddonSetupCode = generateAddonSetupCode;
23
- //# sourceMappingURL=codegen-set-addon-channel.js.map
25
+ }
@@ -0,0 +1 @@
1
+ "use strict";
@@ -0,0 +1 @@
1
+ "use strict";
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.allowedEnvPrefix = void 0;
7
+ exports.stringifyProcessEnvs = stringifyProcessEnvs;
8
+
9
+ var _coreCommon = require("@storybook/core-common");
10
+
11
+ // Allowed env variables on the client
12
+ const allowedEnvVariables = ['STORYBOOK', // Vite `import.meta.env` default variables
13
+ // @see https://github.com/vitejs/vite/blob/6b8d94dca2a1a8b4952e3e3fcd0aed1aedb94215/packages/vite/types/importMeta.d.ts#L68-L75
14
+ 'BASE_URL', 'MODE', 'DEV', 'PROD', 'SSR']; // Env variables starts with env prefix will be exposed to your client source code via `import.meta.env`
15
+
16
+ const allowedEnvPrefix = ['VITE_', 'STORYBOOK_'];
17
+ /**
18
+ * Customized version of stringifyProcessEnvs from @storybook/core-common which
19
+ * uses import.meta.env instead of process.env and checks for allowed variables.
20
+ */
21
+
22
+ exports.allowedEnvPrefix = allowedEnvPrefix;
23
+
24
+ function stringifyProcessEnvs(raw, envPrefix) {
25
+ const updatedRaw = {};
26
+ const envs = Object.entries(raw).reduce((acc, [key, value]) => {
27
+ // Only add allowed values OR values from array OR string started with allowed prefixes
28
+ if (allowedEnvVariables.includes(key) || Array.isArray(envPrefix) && !!envPrefix.find(prefix => key.startsWith(prefix)) || typeof envPrefix === 'string' && key.startsWith(envPrefix)) {
29
+ acc[`import.meta.env.${key}`] = JSON.stringify(value);
30
+ updatedRaw[key] = value;
31
+ }
32
+
33
+ return acc;
34
+ }, {
35
+ // Default fallback
36
+ 'process.env.XSTORYBOOK_EXAMPLE_APP': '""'
37
+ }); // support destructuring like
38
+ // const { foo } = import.meta.env;
39
+
40
+ envs['import.meta.env'] = JSON.stringify((0, _coreCommon.stringifyEnvs)(updatedRaw));
41
+ return envs;
42
+ }
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.start = exports.build = void 0;
7
+
8
+ var fs = _interopRequireWildcard(require("fs"));
9
+
10
+ var path = _interopRequireWildcard(require("path"));
11
+
12
+ var _transformIframeHtml = require("./transform-iframe-html");
13
+
14
+ var _viteServer = require("./vite-server");
15
+
16
+ var _build = require("./build");
17
+
18
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
19
+
20
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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; }
21
+
22
+ // noinspection JSUnusedGlobalSymbols
23
+ function iframeMiddleware(options, server) {
24
+ return async (req, res, next) => {
25
+ if (!req.url.match(/^\/iframe\.html($|\?)/)) {
26
+ next();
27
+ return;
28
+ } // We need to handle `html-proxy` params for style tag HMR https://github.com/storybookjs/builder-vite/issues/266#issuecomment-1055677865
29
+ // e.g. /iframe.html?html-proxy&index=0.css
30
+
31
+
32
+ if (req.query['html-proxy'] !== undefined) {
33
+ next();
34
+ return;
35
+ }
36
+
37
+ const indexHtml = fs.readFileSync(path.resolve(__dirname, '../..', 'input', 'iframe.html'), 'utf-8');
38
+ const generated = await (0, _transformIframeHtml.transformIframeHtml)(indexHtml, options);
39
+ const transformed = await server.transformIndexHtml('/iframe.html', generated);
40
+ res.setHeader('Content-Type', 'text/html');
41
+ res.status(200).send(transformed);
42
+ };
43
+ }
44
+
45
+ const start = async ({
46
+ startTime,
47
+ options,
48
+ router,
49
+ server: devServer
50
+ }) => {
51
+ const server = await (0, _viteServer.createViteServer)(options, devServer); // Just mock this endpoint (which is really Webpack-specific) so we don't get spammed with 404 in browser devtools
52
+ // TODO: we should either show some sort of progress from Vite, or just try to disable the whole Loader in the Manager UI.
53
+
54
+ router.get('/progress', (req, res) => {
55
+ res.header('Cache-Control', 'no-cache');
56
+ res.header('Content-Type', 'text/event-stream');
57
+ });
58
+ router.use(iframeMiddleware(options, server));
59
+ router.use(server.middlewares);
60
+
61
+ async function bail(e) {
62
+ try {
63
+ return await server.close();
64
+ } catch (err) {
65
+ console.warn('unable to close vite server');
66
+ }
67
+
68
+ throw e;
69
+ }
70
+
71
+ return {
72
+ bail,
73
+ stats: {
74
+ toJson: () => null
75
+ },
76
+ totalTime: process.hrtime(startTime)
77
+ };
78
+ };
79
+
80
+ exports.start = start;
81
+
82
+ const build = async ({
83
+ options
84
+ }) => {
85
+ return (0, _build.build)(options);
86
+ };
87
+
88
+ exports.build = build;