histoire 0.11.2 → 0.11.3

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.
@@ -3,10 +3,12 @@ import type { ServerStoryFile } from '@histoire/shared';
3
3
  import type { Context } from '../context.js';
4
4
  export interface UseCollectStoriesOptions {
5
5
  server: ViteDevServer;
6
+ mainServer?: ViteDevServer;
6
7
  throws?: boolean;
7
8
  }
8
9
  export declare function useCollectStories(options: UseCollectStoriesOptions, ctx: Context): {
9
10
  clearCache: () => void;
10
11
  executeStoryFile: (storyFile: ServerStoryFile) => Promise<void>;
11
12
  destroy: () => Promise<void>;
13
+ clearInvalidates: () => void;
12
14
  };
@@ -6,8 +6,9 @@ import Tinypool from 'tinypool';
6
6
  import { createBirpc } from 'birpc';
7
7
  import { cpus } from 'node:os';
8
8
  import { createPath } from '../tree.js';
9
+ import { slash } from '../util/fs.js';
9
10
  export function useCollectStories(options, ctx) {
10
- const { server } = options;
11
+ const { server, mainServer } = options;
11
12
  const node = new ViteNodeServer(server, {
12
13
  deps: {
13
14
  inline: [
@@ -24,12 +25,13 @@ export function useCollectStories(options, ctx) {
24
25
  const threadsCount = ctx.mode === 'dev'
25
26
  ? Math.max(cpus().length / 2, 1)
26
27
  : Math.max(cpus().length - 1, 1);
28
+ console.log(pc.blue(`Using ${threadsCount} threads for story collection`));
27
29
  const threadPool = new Tinypool({
28
30
  filename: new URL('./worker.js', import.meta.url).href,
29
31
  // WebContainer compatibility (Stackblitz)
30
32
  useAtomics: typeof process.versions.webcontainer !== 'string',
31
- maxThreads: threadsCount,
32
33
  minThreads: threadsCount,
34
+ maxThreads: threadsCount,
33
35
  });
34
36
  function clearCache() {
35
37
  server.moduleGraph.invalidateAll();
@@ -51,15 +53,29 @@ export function useCollectStories(options, ctx) {
51
53
  workerPort,
52
54
  };
53
55
  }
56
+ const invalidates = new Set();
57
+ if (mainServer) {
58
+ mainServer.watcher.on('change', (file) => {
59
+ file = slash(file);
60
+ if (invalidates.has(file))
61
+ return;
62
+ invalidates.add(file);
63
+ });
64
+ }
65
+ function clearInvalidates() {
66
+ invalidates.clear();
67
+ }
54
68
  async function executeStoryFile(storyFile) {
55
69
  try {
56
70
  const { workerPort } = createChannel();
57
- const { storyData } = await threadPool.run({
71
+ const payload = {
58
72
  root: server.config.root,
59
73
  base: server.config.base,
60
74
  storyFile,
61
75
  port: workerPort,
62
- }, {
76
+ invalidates: Array.from(invalidates),
77
+ };
78
+ const { storyData } = await threadPool.run(payload, {
63
79
  transferList: [
64
80
  workerPort,
65
81
  ],
@@ -106,5 +122,6 @@ export function useCollectStories(options, ctx) {
106
122
  clearCache,
107
123
  executeStoryFile,
108
124
  destroy,
125
+ clearInvalidates,
109
126
  };
110
127
  }
@@ -6,6 +6,7 @@ export interface Payload {
6
6
  base: string;
7
7
  port: MessagePort;
8
8
  storyFile: ServerStoryFile;
9
+ invalidates: string[];
9
10
  }
10
11
  export interface ReturnData {
11
12
  storyData: ServerStory[];
@@ -1,38 +1,52 @@
1
1
  import { fileURLToPath } from 'node:url';
2
- import { ViteNodeRunner } from 'vite-node/client';
2
+ import { performance } from 'node:perf_hooks';
3
+ import { ModuleCacheMap, ViteNodeRunner } from 'vite-node/client';
3
4
  import { createBirpc } from 'birpc';
4
5
  import { dirname, resolve } from 'pathe';
6
+ import pc from 'picocolors';
5
7
  import { createDomEnv } from '../dom/env.js';
6
8
  const __dirname = dirname(fileURLToPath(import.meta.url));
9
+ const _moduleCache = new ModuleCacheMap();
10
+ let _runner;
11
+ let _rpc;
7
12
  export default async (payload) => {
13
+ const startTime = performance.now();
8
14
  process.env.HST_COLLECT = 'true';
9
- const rpc = createBirpc({}, {
15
+ _rpc = createBirpc({}, {
10
16
  post: data => payload.port.postMessage(data),
11
17
  on: data => payload.port.on('message', data),
12
18
  });
13
- const runner = new ViteNodeRunner({
19
+ const runner = _runner ?? (_runner = new ViteNodeRunner({
14
20
  root: payload.root,
15
21
  base: payload.base,
22
+ moduleCache: _moduleCache,
16
23
  fetchModule(id) {
17
- return rpc.fetchModule(id);
24
+ return _rpc.fetchModule(id);
18
25
  },
19
26
  resolveId(id, importer) {
20
- return rpc.resolveId(id, importer);
27
+ return _rpc.resolveId(id, importer);
21
28
  },
22
- });
29
+ }));
30
+ // Cleanup cache
31
+ for (const file of payload.invalidates) {
32
+ _moduleCache.delete(file);
33
+ }
23
34
  const { destroy: destroyDomEnv } = createDomEnv();
24
35
  if (!global.CSS.supports) {
25
36
  global.CSS.supports = () => false;
26
37
  }
27
38
  const el = window.document.createElement('div');
39
+ const beforeExectureTime = performance.now();
28
40
  // Mount app to collect stories/variants
29
41
  const { run } = (await runner.executeFile(resolve(__dirname, './run.js')));
42
+ const afterExectureTime = performance.now();
30
43
  const storyData = [];
31
44
  await run({
32
45
  file: payload.storyFile,
33
46
  storyData,
34
47
  el,
35
48
  });
49
+ const afterRunTime = performance.now();
36
50
  if (payload.storyFile.markdownFile) {
37
51
  const el = document.createElement('div');
38
52
  el.innerHTML = payload.storyFile.markdownFile.html;
@@ -42,6 +56,8 @@ export default async (payload) => {
42
56
  });
43
57
  }
44
58
  destroyDomEnv();
59
+ const endTime = performance.now();
60
+ console.log(pc.dim(`${payload.storyFile.relativePath} ${Math.round(endTime - startTime)}ms (setup:${Math.round(beforeExectureTime - startTime)}ms, execute:${Math.round(afterExectureTime - beforeExectureTime)}ms, run:${Math.round(afterRunTime - afterExectureTime)}ms)`));
45
61
  return {
46
62
  storyData,
47
63
  };
@@ -1,15 +1,15 @@
1
+ import chokidar from 'chokidar';
2
+ import pc from 'picocolors';
1
3
  import { resolveConfigFile } from '../config.js';
2
4
  import { createContext } from '../context.js';
3
5
  import { createServer } from '../server.js';
4
- import chokidar from 'chokidar';
5
- import pc from 'picocolors';
6
6
  export async function devCommand(options) {
7
7
  let stop;
8
8
  async function start() {
9
9
  const ctx = await createContext({
10
10
  mode: 'dev',
11
11
  });
12
- const { server, close } = await createServer(ctx, options.port ?? 6006);
12
+ const { server, close } = await createServer(ctx, { port: options.port });
13
13
  server.printUrls();
14
14
  // Histoire config watcher
15
15
  let watcher;
@@ -7,6 +7,7 @@ import emoji from 'markdown-it-emoji';
7
7
  import chokidar from 'chokidar';
8
8
  import fs from 'fs-extra';
9
9
  import path from 'pathe';
10
+ import { paramCase } from 'change-case';
10
11
  import { slugify } from './util/slugify.js';
11
12
  import { addStory, notifyStoryChange, removeStory } from './stories.js';
12
13
  const onMarkdownListChangeHandlers = [];
@@ -87,27 +88,6 @@ export async function createMarkdownPlugins(ctx) {
87
88
  }`;
88
89
  },
89
90
  });
90
- plugins.push({
91
- name: 'histoire-markdown-files',
92
- transform(code, id) {
93
- if (id.endsWith('.story.md')) {
94
- const relativePath = path.relative(ctx.root, id);
95
- const { content, data: frontmatter } = matter(code);
96
- const html = md.render(content);
97
- return `export const html = ${JSON.stringify(html)}
98
- export const frontmatter = ${JSON.stringify(frontmatter)}
99
- export const relativePath = ${JSON.stringify(relativePath)}
100
-
101
- if (import.meta.hot) {
102
- import.meta.hot.accept(newModule => {
103
- if (newModule) {
104
- window.__hst_md_hmr(newModule)
105
- }
106
- })
107
- }`;
108
- }
109
- },
110
- });
111
91
  return plugins;
112
92
  }
113
93
  export async function createMarkdownFilesWatcher(ctx) {
@@ -124,6 +104,7 @@ export async function createMarkdownFilesWatcher(ctx) {
124
104
  const { data: frontmatter, content } = matter(await fs.readFile(absolutePath, 'utf8'));
125
105
  const html = md.render(content);
126
106
  const file = {
107
+ id: paramCase(relativePath.toLowerCase()),
127
108
  relativePath,
128
109
  absolutePath,
129
110
  isRelatedToStory,
@@ -1,5 +1,8 @@
1
1
  import { Context } from './context.js';
2
- export declare function createServer(ctx: Context, port: number): Promise<{
2
+ export interface CreateServerOptions {
3
+ port?: number;
4
+ }
5
+ export declare function createServer(ctx: Context, options?: CreateServerOptions): Promise<{
3
6
  server: import("vite").ViteDevServer;
4
7
  close: () => Promise<void>;
5
8
  }>;
@@ -1,4 +1,6 @@
1
+ import { performance } from 'node:perf_hooks';
1
2
  import { createServer as createViteServer } from 'vite';
3
+ import pc from 'picocolors';
2
4
  import { getViteConfigWithPlugins, RESOLVED_MARKDOWN_FILES, RESOLVED_SEARCH_TITLE_DATA_ID, RESOLVED_STORIES_ID } from './vite.js';
3
5
  import { onStoryChange, onStoryListChange, watchStories } from './stories.js';
4
6
  import { useCollectStories } from './collect/index.js';
@@ -6,16 +8,21 @@ import { DevPluginApi } from './plugin.js';
6
8
  import { useModuleLoader } from './load.js';
7
9
  import { wrapLogError } from './util/log.js';
8
10
  import { createMarkdownFilesWatcher, onMarkdownListChange } from './markdown.js';
9
- export async function createServer(ctx, port) {
10
- const server = await createViteServer(await getViteConfigWithPlugins(false, ctx));
11
- await server.pluginContainer.buildStart({});
12
- const nodeServer = await createViteServer(await getViteConfigWithPlugins(true, ctx));
13
- await nodeServer.pluginContainer.buildStart({});
11
+ export async function createServer(ctx, options = {}) {
12
+ const getViteServer = async (collecting) => {
13
+ const server = await createViteServer(await getViteConfigWithPlugins(collecting, ctx));
14
+ await server.pluginContainer.buildStart({});
15
+ return server;
16
+ };
17
+ const [server, nodeServer, , { stop: stopMdFileWatcher },] = await Promise.all([
18
+ getViteServer(false),
19
+ getViteServer(true),
20
+ watchStories(ctx),
21
+ createMarkdownFilesWatcher(ctx),
22
+ ]);
14
23
  const moduleLoader = useModuleLoader({
15
24
  server: nodeServer,
16
25
  });
17
- await watchStories(ctx);
18
- const { stop: stopMdFileWatcher } = await createMarkdownFilesWatcher(ctx);
19
26
  const pluginOnCleanups = [];
20
27
  for (const plugin of ctx.config.plugins) {
21
28
  if (plugin.onDev) {
@@ -27,16 +34,16 @@ export async function createServer(ctx, port) {
27
34
  }
28
35
  }
29
36
  // Wait for pre-bundling (in `listen()`)
30
- await server.listen(port);
31
- const { clearCache, executeStoryFile, destroy: destroyCollectStories, } = useCollectStories({
37
+ await server.listen(options.port ?? server.config.server?.port);
38
+ const { clearCache, executeStoryFile, destroy: destroyCollectStories, clearInvalidates, } = useCollectStories({
32
39
  server: nodeServer,
40
+ mainServer: server,
33
41
  }, ctx);
34
42
  // onStoryChange debouncing
35
- let queue;
36
- let queueResolve;
37
43
  let queued = false;
38
44
  let queuedFiles = [];
39
- let queuedAll = false;
45
+ let queueTimer;
46
+ let collecting = false;
40
47
  let didAllStoriesYet = false;
41
48
  // Invalidate modules
42
49
  const invalidateModule = (id) => {
@@ -64,37 +71,33 @@ export async function createServer(ctx, port) {
64
71
  if (changedFile && !didAllStoriesYet) {
65
72
  return;
66
73
  }
67
- if (queue) {
68
- if (queued) {
69
- if (changedFile) {
70
- if (!queuedFiles.includes(changedFile)) {
71
- queuedFiles.push(changedFile);
72
- }
73
- }
74
- else {
75
- queuedAll = true;
76
- }
77
- return;
78
- }
79
- else if (queuedFiles.includes(changedFile)) {
80
- return;
74
+ if (changedFile) {
75
+ if (!queuedFiles.includes(changedFile)) {
76
+ queuedFiles.push(changedFile);
81
77
  }
82
- else {
83
- queued = true;
84
- // Next call
85
- await queue;
78
+ }
79
+ else {
80
+ queuedFiles = [];
81
+ }
82
+ if (!queued) {
83
+ queued = true;
84
+ if (!collecting) {
85
+ clearTimeout(queueTimer);
86
+ // Debounce
87
+ queueTimer = setTimeout(collect, 100);
86
88
  }
87
89
  }
88
- queuedFiles.unshift(changedFile);
89
- queued = false;
90
- queue = new Promise(resolve => {
91
- queueResolve = resolve;
92
- });
90
+ });
91
+ async function collect() {
92
+ collecting = true;
93
93
  clearCache();
94
- console.log('Collect stories start', changedFile?.path ?? 'all');
95
- const time = Date.now();
96
- if (changedFile && !queuedAll) {
97
- await Promise.all(queuedFiles.map(async (storyFile) => {
94
+ const currentFiles = queuedFiles.slice();
95
+ queuedFiles = [];
96
+ queued = false;
97
+ console.log('Collect stories start', currentFiles.length ? currentFiles.map(f => f.fileName).join(', ') : 'all');
98
+ const time = performance.now();
99
+ if (currentFiles.length) {
100
+ await Promise.all(currentFiles.map(async (storyFile) => {
98
101
  await executeStoryFile(storyFile);
99
102
  if (storyFile.story) {
100
103
  await invalidateModule(`/__resolved__virtual:story-source:${storyFile.story.id}`);
@@ -121,13 +124,15 @@ export async function createServer(ctx, port) {
121
124
  didAllStoriesYet = true;
122
125
  server.ws.send('histoire:all-stories-loaded', {});
123
126
  }
124
- console.log('Collect stories end', Date.now() - time, 'ms');
125
- queuedFiles = [];
126
- queuedAll = false;
127
- queueResolve();
127
+ console.log(`Collect stories end ${pc.bold(pc.blue(Math.round(performance.now() - time)))}ms`);
128
+ clearInvalidates();
128
129
  invalidateModule(RESOLVED_STORIES_ID);
129
130
  invalidateModule(RESOLVED_SEARCH_TITLE_DATA_ID);
130
- });
131
+ collecting = false;
132
+ if (queued) {
133
+ await collect();
134
+ }
135
+ }
131
136
  onStoryListChange(() => {
132
137
  invalidateModule(RESOLVED_STORIES_ID);
133
138
  invalidateModule(RESOLVED_SEARCH_TITLE_DATA_ID);
@@ -144,6 +149,7 @@ export async function createServer(ctx, port) {
144
149
  await wrapLogError('destroyCollectStories', () => destroyCollectStories());
145
150
  await wrapLogError('stopMdFileWatcher', () => stopMdFileWatcher());
146
151
  }
152
+ collect();
147
153
  return {
148
154
  server,
149
155
  close,
@@ -0,0 +1 @@
1
+ export declare const slash: (str: string) => string;
@@ -0,0 +1 @@
1
+ export const slash = (str) => str.replace(/\\/g, '/');
package/dist/node/vite.js CHANGED
@@ -3,6 +3,7 @@ import { relative, resolve, join, dirname } from 'pathe';
3
3
  import { resolveConfig as resolveViteConfigInternal, mergeConfig as mergeViteConfig, loadConfigFromFile as loadViteConfigFromFile, } from 'vite';
4
4
  import { lookup as lookupMime } from 'mrmime';
5
5
  import fs from 'fs-extra';
6
+ import ViteInspect from 'vite-plugin-inspect';
6
7
  import { APP_PATH, TEMP_PATH } from './alias.js';
7
8
  import { notifyStoryChange } from './stories.js';
8
9
  import { makeTree } from './tree.js';
@@ -86,8 +87,9 @@ async function mergeHistoireViteConfig(viteConfig, ctx) {
86
87
  }
87
88
  export async function getViteConfigWithPlugins(isServer, ctx) {
88
89
  const resolvedViteConfig = await resolveViteConfig(ctx);
89
- const userViteConfig = await loadViteConfigFromFile({ command: ctx.mode === 'dev' ? 'serve' : 'build', mode: ctx.mode });
90
- const inlineConfig = await mergeHistoireViteConfig(userViteConfig?.config ?? {}, ctx);
90
+ const userViteConfigFile = await loadViteConfigFromFile({ command: ctx.mode === 'dev' ? 'serve' : 'build', mode: ctx.mode });
91
+ const userViteConfig = mergeViteConfig(userViteConfigFile?.config ?? {}, { server: { port: 6006 } });
92
+ const inlineConfig = await mergeHistoireViteConfig(userViteConfig, ctx);
91
93
  const plugins = [];
92
94
  const hasPnpm = !!(await findUp(ctx.root, ['pnpm-lock.yaml']));
93
95
  function optimizeDeps(deps) {
@@ -105,6 +107,7 @@ export async function getViteConfigWithPlugins(isServer, ctx) {
105
107
  }
106
108
  return result;
107
109
  }
110
+ plugins.push(ViteInspect());
108
111
  plugins.push({
109
112
  name: 'histoire-vite-plugin',
110
113
  config() {
@@ -169,19 +172,19 @@ export async function getViteConfigWithPlugins(isServer, ctx) {
169
172
  if (typeof setupFileConfig === 'string') {
170
173
  file = setupFileConfig;
171
174
  }
172
- else if (isServer) {
175
+ else if (isServer && 'server' in setupFileConfig) {
173
176
  file = setupFileConfig.server;
174
177
  }
175
- else {
178
+ else if ('browser' in setupFileConfig) {
176
179
  file = setupFileConfig.browser;
177
180
  }
178
- return this.resolve(resolve(ctx.root, file), importer, {
179
- skipSelf: true,
180
- });
181
- }
182
- else {
183
- return NOOP_ID;
181
+ if (file) {
182
+ return this.resolve(resolve(ctx.root, file), importer, {
183
+ skipSelf: true,
184
+ });
185
+ }
184
186
  }
187
+ return NOOP_ID;
185
188
  }
186
189
  if (id.startsWith(CONFIG_ID)) {
187
190
  return RESOLVED_CONFIG_ID;
@@ -219,6 +222,11 @@ export async function getViteConfigWithPlugins(isServer, ctx) {
219
222
  // @TODO
220
223
  // return `\0${id}`
221
224
  }
225
+ if (id.startsWith('virtual:md:')) {
226
+ return `/__resolved__${id}`;
227
+ // @TODO
228
+ // return `\0${id}`
229
+ }
222
230
  },
223
231
  async load(id) {
224
232
  if (id === RESOLVED_STORIES_ID) {
@@ -333,7 +341,7 @@ if (import.meta.hot) {
333
341
  }`;
334
342
  }
335
343
  if (id === RESOLVED_MARKDOWN_FILES) {
336
- const filesJs = ctx.markdownFiles.map(f => `${JSON.stringify(f.relativePath)}: () => import(${JSON.stringify(`/${f.relativePath}`)})`).join(',');
344
+ const filesJs = ctx.markdownFiles.map(f => `${JSON.stringify(f.relativePath)}: () => import(${JSON.stringify(`virtual:md:${f.id}`)})`).join(',');
337
345
  return `import { reactive } from ${getInjectedImport('@histoire/vendors/vue')}
338
346
  export const markdownFiles = reactive({${filesJs}})
339
347
  if (import.meta.hot) {
@@ -369,6 +377,25 @@ if (import.meta.hot) {
369
377
  return `export default ${JSON.stringify(source)}`;
370
378
  }
371
379
  }
380
+ if (id.startsWith('/__resolved__virtual:md:')) {
381
+ const fileId = id.slice('/__resolved__virtual:md:'.length);
382
+ const file = ctx.markdownFiles.find(f => f.id === fileId);
383
+ if (!file) {
384
+ throw new Error(`Markdown file not found: ${fileId}`);
385
+ }
386
+ const { html, frontmatter, relativePath } = file;
387
+ return `export const html = ${JSON.stringify(html)}
388
+ export const frontmatter = ${JSON.stringify(frontmatter)}
389
+ export const relativePath = ${JSON.stringify(relativePath)}
390
+
391
+ if (import.meta.hot) {
392
+ import.meta.hot.accept(newModule => {
393
+ if (newModule) {
394
+ window.__hst_md_hmr(newModule)
395
+ }
396
+ })
397
+ }`;
398
+ }
372
399
  },
373
400
  handleHotUpdate(updateContext) {
374
401
  const story = ctx.storyFiles.find(file => file.path === updateContext.file);
@@ -377,8 +404,12 @@ if (import.meta.hot) {
377
404
  }
378
405
  },
379
406
  configureServer(server) {
407
+ let firstMount = true;
380
408
  server.ws.on('histoire:mount', () => {
381
- notifyStoryChange();
409
+ if (!firstMount) {
410
+ notifyStoryChange();
411
+ }
412
+ firstMount = false;
382
413
  });
383
414
  server.middlewares.use(async (req, res, next) => {
384
415
  if (req.url.startsWith(`${server.config.base}__sandbox`)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "histoire",
3
- "version": "0.11.2",
3
+ "version": "0.11.3",
4
4
  "description": "A fast story book powered by Vite",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -33,10 +33,10 @@
33
33
  "histoire": "./bin.mjs"
34
34
  },
35
35
  "dependencies": {
36
- "@histoire/app": "^0.11.2",
37
- "@histoire/controls": "^0.11.2",
38
- "@histoire/shared": "^0.11.2",
39
- "@histoire/vendors": "^0.11.2",
36
+ "@histoire/app": "^0.11.3",
37
+ "@histoire/controls": "^0.11.3",
38
+ "@histoire/shared": "^0.11.3",
39
+ "@histoire/vendors": "^0.11.3",
40
40
  "@types/flexsearch": "^0.7.3",
41
41
  "@types/markdown-it": "^12.2.3",
42
42
  "birpc": "^0.1.1",
@@ -63,6 +63,7 @@
63
63
  "shiki": "0.10.1",
64
64
  "sirv": "^2.0.2",
65
65
  "tinypool": "^0.1.2",
66
+ "vite-plugin-inspect": "^0.7.5",
66
67
  "vite-node": "0.23.4"
67
68
  },
68
69
  "peerDependencies": {
@@ -11,14 +11,16 @@ import type { ServerStoryFile } from '@histoire/shared'
11
11
  import { createPath } from '../tree.js'
12
12
  import type { Context } from '../context.js'
13
13
  import type { Payload, ReturnData } from './worker.js'
14
+ import { slash } from '../util/fs.js'
14
15
 
15
16
  export interface UseCollectStoriesOptions {
16
17
  server: ViteDevServer
18
+ mainServer?: ViteDevServer
17
19
  throws?: boolean
18
20
  }
19
21
 
20
22
  export function useCollectStories (options: UseCollectStoriesOptions, ctx: Context) {
21
- const { server } = options
23
+ const { server, mainServer } = options
22
24
 
23
25
  const node = new ViteNodeServer(server, {
24
26
  deps: {
@@ -37,13 +39,14 @@ export function useCollectStories (options: UseCollectStoriesOptions, ctx: Conte
37
39
  const threadsCount = ctx.mode === 'dev'
38
40
  ? Math.max(cpus().length / 2, 1)
39
41
  : Math.max(cpus().length - 1, 1)
42
+ console.log(pc.blue(`Using ${threadsCount} threads for story collection`))
40
43
 
41
44
  const threadPool = new Tinypool({
42
45
  filename: new URL('./worker.js', import.meta.url).href,
43
46
  // WebContainer compatibility (Stackblitz)
44
47
  useAtomics: typeof process.versions.webcontainer !== 'string',
45
- maxThreads: threadsCount,
46
48
  minThreads: threadsCount,
49
+ maxThreads: threadsCount,
47
50
  })
48
51
 
49
52
  function clearCache () {
@@ -73,15 +76,31 @@ export function useCollectStories (options: UseCollectStoriesOptions, ctx: Conte
73
76
  }
74
77
  }
75
78
 
79
+ const invalidates = new Set<string>()
80
+
81
+ if (mainServer) {
82
+ mainServer.watcher.on('change', (file) => {
83
+ file = slash(file)
84
+ if (invalidates.has(file)) return
85
+ invalidates.add(file)
86
+ })
87
+ }
88
+
89
+ function clearInvalidates () {
90
+ invalidates.clear()
91
+ }
92
+
76
93
  async function executeStoryFile (storyFile: ServerStoryFile) {
77
94
  try {
78
95
  const { workerPort } = createChannel()
79
- const { storyData } = await threadPool.run({
96
+ const payload: Payload = {
80
97
  root: server.config.root,
81
98
  base: server.config.base,
82
99
  storyFile,
83
100
  port: workerPort,
84
- } as Payload, {
101
+ invalidates: Array.from(invalidates),
102
+ }
103
+ const { storyData } = await threadPool.run(payload, {
85
104
  transferList: [
86
105
  workerPort,
87
106
  ],
@@ -132,5 +151,6 @@ export function useCollectStories (options: UseCollectStoriesOptions, ctx: Conte
132
151
  clearCache,
133
152
  executeStoryFile,
134
153
  destroy,
154
+ clearInvalidates,
135
155
  }
136
156
  }
@@ -1,9 +1,11 @@
1
1
  import { fileURLToPath } from 'node:url'
2
2
  import type { MessagePort } from 'node:worker_threads'
3
- import { ViteNodeRunner } from 'vite-node/client'
3
+ import { performance } from 'node:perf_hooks'
4
+ import { ModuleCacheMap, ViteNodeRunner } from 'vite-node/client'
4
5
  import { createBirpc } from 'birpc'
5
6
  import type { FetchFunction, ResolveIdFunction } from 'vite-node'
6
7
  import { dirname, resolve } from 'pathe'
8
+ import pc from 'picocolors'
7
9
  import type { ServerStoryFile, ServerStory, ServerRunPayload } from '@histoire/shared'
8
10
  import { createDomEnv } from '../dom/env.js'
9
11
 
@@ -14,16 +16,25 @@ export interface Payload {
14
16
  base: string
15
17
  port: MessagePort
16
18
  storyFile: ServerStoryFile
19
+ invalidates: string[]
17
20
  }
18
21
 
19
22
  export interface ReturnData {
20
23
  storyData: ServerStory[]
21
24
  }
22
25
 
26
+ const _moduleCache = new ModuleCacheMap()
27
+ let _runner: ViteNodeRunner
28
+ let _rpc: ReturnType<typeof createBirpc<{
29
+ fetchModule: FetchFunction
30
+ resolveId: ResolveIdFunction
31
+ }>>
32
+
23
33
  export default async (payload: Payload): Promise<ReturnData> => {
34
+ const startTime = performance.now()
24
35
  process.env.HST_COLLECT = 'true'
25
36
 
26
- const rpc = createBirpc<{
37
+ _rpc = createBirpc<{
27
38
  fetchModule: FetchFunction
28
39
  resolveId: ResolveIdFunction
29
40
  }>({}, {
@@ -31,16 +42,22 @@ export default async (payload: Payload): Promise<ReturnData> => {
31
42
  on: data => payload.port.on('message', data),
32
43
  })
33
44
 
34
- const runner = new ViteNodeRunner({
45
+ const runner = _runner ?? (_runner = new ViteNodeRunner({
35
46
  root: payload.root,
36
47
  base: payload.base,
48
+ moduleCache: _moduleCache,
37
49
  fetchModule (id) {
38
- return rpc.fetchModule(id)
50
+ return _rpc.fetchModule(id)
39
51
  },
40
52
  resolveId (id, importer) {
41
- return rpc.resolveId(id, importer)
53
+ return _rpc.resolveId(id, importer)
42
54
  },
43
- })
55
+ }))
56
+
57
+ // Cleanup cache
58
+ for (const file of payload.invalidates) {
59
+ _moduleCache.delete(file)
60
+ }
44
61
 
45
62
  const { destroy: destroyDomEnv } = createDomEnv()
46
63
  if (!global.CSS.supports) {
@@ -49,14 +66,17 @@ export default async (payload: Payload): Promise<ReturnData> => {
49
66
 
50
67
  const el = window.document.createElement('div')
51
68
 
69
+ const beforeExectureTime = performance.now()
52
70
  // Mount app to collect stories/variants
53
71
  const { run } = (await runner.executeFile(resolve(__dirname, './run.js'))) as { run: (payload: ServerRunPayload) => Promise<any> }
72
+ const afterExectureTime = performance.now()
54
73
  const storyData: ServerStory[] = []
55
74
  await run({
56
75
  file: payload.storyFile,
57
76
  storyData,
58
77
  el,
59
78
  })
79
+ const afterRunTime = performance.now()
60
80
 
61
81
  if (payload.storyFile.markdownFile) {
62
82
  const el = document.createElement('div')
@@ -69,6 +89,9 @@ export default async (payload: Payload): Promise<ReturnData> => {
69
89
 
70
90
  destroyDomEnv()
71
91
 
92
+ const endTime = performance.now()
93
+ console.log(pc.dim(`${payload.storyFile.relativePath} ${Math.round(endTime - startTime)}ms (setup:${Math.round(beforeExectureTime - startTime)}ms, execute:${Math.round(afterExectureTime - beforeExectureTime)}ms, run:${Math.round(afterRunTime - afterExectureTime)}ms)`))
94
+
72
95
  return {
73
96
  storyData,
74
97
  }
@@ -1,8 +1,8 @@
1
+ import chokidar from 'chokidar'
2
+ import pc from 'picocolors'
1
3
  import { resolveConfigFile } from '../config.js'
2
4
  import { createContext } from '../context.js'
3
5
  import { createServer } from '../server.js'
4
- import chokidar from 'chokidar'
5
- import pc from 'picocolors'
6
6
 
7
7
  export interface DevOptions {
8
8
  port: number
@@ -15,7 +15,7 @@ export async function devCommand (options: DevOptions) {
15
15
  const ctx = await createContext({
16
16
  mode: 'dev',
17
17
  })
18
- const { server, close } = await createServer(ctx, options.port ?? 6006)
18
+ const { server, close } = await createServer(ctx, { port: options.port })
19
19
  server.printUrls()
20
20
 
21
21
  // Histoire config watcher
@@ -8,6 +8,7 @@ import type { Plugin as VitePlugin } from 'vite'
8
8
  import chokidar from 'chokidar'
9
9
  import fs from 'fs-extra'
10
10
  import path from 'pathe'
11
+ import { paramCase } from 'change-case'
11
12
  import type { ServerMarkdownFile } from '@histoire/shared'
12
13
  import { slugify } from './util/slugify.js'
13
14
  import type { Context } from './context.js'
@@ -103,28 +104,6 @@ export async function createMarkdownPlugins (ctx: Context) {
103
104
  },
104
105
  })
105
106
 
106
- plugins.push({
107
- name: 'histoire-markdown-files',
108
- transform (code, id) {
109
- if (id.endsWith('.story.md')) {
110
- const relativePath = path.relative(ctx.root, id)
111
- const { content, data: frontmatter } = matter(code)
112
- const html = md.render(content)
113
- return `export const html = ${JSON.stringify(html)}
114
- export const frontmatter = ${JSON.stringify(frontmatter)}
115
- export const relativePath = ${JSON.stringify(relativePath)}
116
-
117
- if (import.meta.hot) {
118
- import.meta.hot.accept(newModule => {
119
- if (newModule) {
120
- window.__hst_md_hmr(newModule)
121
- }
122
- })
123
- }`
124
- }
125
- },
126
- })
127
-
128
107
  return plugins
129
108
  }
130
109
 
@@ -146,6 +125,7 @@ export async function createMarkdownFilesWatcher (ctx: Context) {
146
125
  const html = md.render(content)
147
126
 
148
127
  const file: ServerMarkdownFile = {
128
+ id: paramCase(relativePath.toLowerCase()),
149
129
  relativePath,
150
130
  absolutePath,
151
131
  isRelatedToStory,
@@ -1,4 +1,6 @@
1
+ import { performance } from 'node:perf_hooks'
1
2
  import { createServer as createViteServer } from 'vite'
3
+ import pc from 'picocolors'
2
4
  import type { ServerStoryFile } from '@histoire/shared'
3
5
  import { Context } from './context.js'
4
6
  import { getViteConfigWithPlugins, RESOLVED_MARKDOWN_FILES, RESOLVED_SEARCH_TITLE_DATA_ID, RESOLVED_STORIES_ID } from './vite.js'
@@ -9,21 +11,33 @@ import { useModuleLoader } from './load.js'
9
11
  import { wrapLogError } from './util/log.js'
10
12
  import { createMarkdownFilesWatcher, onMarkdownListChange } from './markdown.js'
11
13
 
12
- export async function createServer (ctx: Context, port: number) {
13
- const server = await createViteServer(await getViteConfigWithPlugins(false, ctx))
14
- await server.pluginContainer.buildStart({})
14
+ export interface CreateServerOptions {
15
+ port?: number
16
+ }
17
+
18
+ export async function createServer (ctx: Context, options: CreateServerOptions = {}) {
19
+ const getViteServer = async (collecting: boolean) => {
20
+ const server = await createViteServer(await getViteConfigWithPlugins(collecting, ctx))
21
+ await server.pluginContainer.buildStart({})
22
+ return server
23
+ }
15
24
 
16
- const nodeServer = await createViteServer(await getViteConfigWithPlugins(true, ctx))
17
- await nodeServer.pluginContainer.buildStart({})
25
+ const [
26
+ server,
27
+ nodeServer,
28
+ ,
29
+ { stop: stopMdFileWatcher },
30
+ ] = await Promise.all([
31
+ getViteServer(false),
32
+ getViteServer(true),
33
+ watchStories(ctx),
34
+ createMarkdownFilesWatcher(ctx),
35
+ ] as const)
18
36
 
19
37
  const moduleLoader = useModuleLoader({
20
38
  server: nodeServer,
21
39
  })
22
40
 
23
- await watchStories(ctx)
24
-
25
- const { stop: stopMdFileWatcher } = await createMarkdownFilesWatcher(ctx)
26
-
27
41
  const pluginOnCleanups: (() => void | Promise<void>)[] = []
28
42
  for (const plugin of ctx.config.plugins) {
29
43
  if (plugin.onDev) {
@@ -36,22 +50,23 @@ export async function createServer (ctx: Context, port: number) {
36
50
  }
37
51
 
38
52
  // Wait for pre-bundling (in `listen()`)
39
- await server.listen(port)
53
+ await server.listen(options.port ?? server.config.server?.port)
40
54
 
41
55
  const {
42
56
  clearCache,
43
57
  executeStoryFile,
44
58
  destroy: destroyCollectStories,
59
+ clearInvalidates,
45
60
  } = useCollectStories({
46
61
  server: nodeServer,
62
+ mainServer: server,
47
63
  }, ctx)
48
64
 
49
65
  // onStoryChange debouncing
50
- let queue: Promise<void>
51
- let queueResolve: () => void
52
66
  let queued = false
53
67
  let queuedFiles: ServerStoryFile[] = []
54
- let queuedAll = false
68
+ let queueTimer
69
+ let collecting = false
55
70
  let didAllStoriesYet = false
56
71
 
57
72
  // Invalidate modules
@@ -82,36 +97,38 @@ export async function createServer (ctx: Context, port: number) {
82
97
  if (changedFile && !didAllStoriesYet) {
83
98
  return
84
99
  }
85
- if (queue) {
86
- if (queued) {
87
- if (changedFile) {
88
- if (!queuedFiles.includes(changedFile)) {
89
- queuedFiles.push(changedFile)
90
- }
91
- } else {
92
- queuedAll = true
93
- }
94
- return
95
- } else if (queuedFiles.includes(changedFile)) {
96
- return
97
- } else {
98
- queued = true
99
- // Next call
100
- await queue
100
+
101
+ if (changedFile) {
102
+ if (!queuedFiles.includes(changedFile)) {
103
+ queuedFiles.push(changedFile)
101
104
  }
105
+ } else {
106
+ queuedFiles = []
102
107
  }
103
- queuedFiles.unshift(changedFile)
104
- queued = false
105
- queue = new Promise(resolve => {
106
- queueResolve = resolve
107
- })
108
+
109
+ if (!queued) {
110
+ queued = true
111
+ if (!collecting) {
112
+ clearTimeout(queueTimer)
113
+ // Debounce
114
+ queueTimer = setTimeout(collect, 100)
115
+ }
116
+ }
117
+ })
118
+
119
+ async function collect () {
120
+ collecting = true
108
121
 
109
122
  clearCache()
110
123
 
111
- console.log('Collect stories start', changedFile?.path ?? 'all')
112
- const time = Date.now()
113
- if (changedFile && !queuedAll) {
114
- await Promise.all(queuedFiles.map(async storyFile => {
124
+ const currentFiles = queuedFiles.slice()
125
+ queuedFiles = []
126
+ queued = false
127
+
128
+ console.log('Collect stories start', currentFiles.length ? currentFiles.map(f => f.fileName).join(', ') : 'all')
129
+ const time = performance.now()
130
+ if (currentFiles.length) {
131
+ await Promise.all(currentFiles.map(async storyFile => {
115
132
  await executeStoryFile(storyFile)
116
133
  if (storyFile.story) {
117
134
  await invalidateModule(`/__resolved__virtual:story-source:${storyFile.story.id}`)
@@ -141,15 +158,19 @@ export async function createServer (ctx: Context, port: number) {
141
158
  didAllStoriesYet = true
142
159
  server.ws.send('histoire:all-stories-loaded', {})
143
160
  }
144
- console.log('Collect stories end', Date.now() - time, 'ms')
161
+ console.log(`Collect stories end ${pc.bold(pc.blue(Math.round(performance.now() - time)))}ms`)
145
162
 
146
- queuedFiles = []
147
- queuedAll = false
148
- queueResolve()
163
+ clearInvalidates()
149
164
 
150
165
  invalidateModule(RESOLVED_STORIES_ID)
151
166
  invalidateModule(RESOLVED_SEARCH_TITLE_DATA_ID)
152
- })
167
+
168
+ collecting = false
169
+
170
+ if (queued) {
171
+ await collect()
172
+ }
173
+ }
153
174
 
154
175
  onStoryListChange(() => {
155
176
  invalidateModule(RESOLVED_STORIES_ID)
@@ -170,6 +191,8 @@ export async function createServer (ctx: Context, port: number) {
170
191
  await wrapLogError('stopMdFileWatcher', () => stopMdFileWatcher())
171
192
  }
172
193
 
194
+ collect()
195
+
173
196
  return {
174
197
  server,
175
198
  close,
@@ -0,0 +1 @@
1
+ export const slash = (str: string) => str.replace(/\\/g, '/')
package/src/node/vite.ts CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  } from 'vite'
12
12
  import { lookup as lookupMime } from 'mrmime'
13
13
  import fs from 'fs-extra'
14
+ import ViteInspect from 'vite-plugin-inspect'
14
15
  import { APP_PATH, TEMP_PATH } from './alias.js'
15
16
  import { Context } from './context.js'
16
17
  import { notifyStoryChange } from './stories.js'
@@ -105,9 +106,10 @@ async function mergeHistoireViteConfig (viteConfig: InlineConfig, ctx: Context)
105
106
  export async function getViteConfigWithPlugins (isServer: boolean, ctx: Context): Promise<InlineConfig> {
106
107
  const resolvedViteConfig = await resolveViteConfig(ctx)
107
108
 
108
- const userViteConfig = await loadViteConfigFromFile({ command: ctx.mode === 'dev' ? 'serve' : 'build', mode: ctx.mode })
109
+ const userViteConfigFile = await loadViteConfigFromFile({ command: ctx.mode === 'dev' ? 'serve' : 'build', mode: ctx.mode })
110
+ const userViteConfig = mergeViteConfig(userViteConfigFile?.config ?? {}, { server: { port: 6006 } })
109
111
 
110
- const inlineConfig = await mergeHistoireViteConfig(userViteConfig?.config ?? {}, ctx)
112
+ const inlineConfig = await mergeHistoireViteConfig(userViteConfig, ctx)
111
113
  const plugins: VitePlugin[] = []
112
114
 
113
115
  const hasPnpm = !!(await findUp(ctx.root, ['pnpm-lock.yaml']))
@@ -127,6 +129,8 @@ export async function getViteConfigWithPlugins (isServer: boolean, ctx: Context)
127
129
  return result
128
130
  }
129
131
 
132
+ plugins.push(ViteInspect())
133
+
130
134
  plugins.push({
131
135
  name: 'histoire-vite-plugin',
132
136
 
@@ -192,17 +196,18 @@ export async function getViteConfigWithPlugins (isServer: boolean, ctx: Context)
192
196
  let file: string
193
197
  if (typeof setupFileConfig === 'string') {
194
198
  file = setupFileConfig
195
- } else if (isServer) {
199
+ } else if (isServer && 'server' in setupFileConfig) {
196
200
  file = setupFileConfig.server
197
- } else {
201
+ } else if ('browser' in setupFileConfig) {
198
202
  file = setupFileConfig.browser
199
203
  }
200
- return this.resolve(resolve(ctx.root, file), importer, {
201
- skipSelf: true,
202
- })
203
- } else {
204
- return NOOP_ID
204
+ if (file) {
205
+ return this.resolve(resolve(ctx.root, file), importer, {
206
+ skipSelf: true,
207
+ })
208
+ }
205
209
  }
210
+ return NOOP_ID
206
211
  }
207
212
  if (id.startsWith(CONFIG_ID)) {
208
213
  return RESOLVED_CONFIG_ID
@@ -240,6 +245,12 @@ export async function getViteConfigWithPlugins (isServer: boolean, ctx: Context)
240
245
  // @TODO
241
246
  // return `\0${id}`
242
247
  }
248
+
249
+ if (id.startsWith('virtual:md:')) {
250
+ return `/__resolved__${id}`
251
+ // @TODO
252
+ // return `\0${id}`
253
+ }
243
254
  },
244
255
 
245
256
  async load (id) {
@@ -364,7 +375,7 @@ if (import.meta.hot) {
364
375
  }
365
376
 
366
377
  if (id === RESOLVED_MARKDOWN_FILES) {
367
- const filesJs = ctx.markdownFiles.map(f => `${JSON.stringify(f.relativePath)}: () => import(${JSON.stringify(`/${f.relativePath}`)})`).join(',')
378
+ const filesJs = ctx.markdownFiles.map(f => `${JSON.stringify(f.relativePath)}: () => import(${JSON.stringify(`virtual:md:${f.id}`)})`).join(',')
368
379
  return `import { reactive } from ${getInjectedImport('@histoire/vendors/vue')}
369
380
  export const markdownFiles = reactive({${filesJs}})
370
381
  if (import.meta.hot) {
@@ -401,6 +412,26 @@ if (import.meta.hot) {
401
412
  return `export default ${JSON.stringify(source)}`
402
413
  }
403
414
  }
415
+
416
+ if (id.startsWith('/__resolved__virtual:md:')) {
417
+ const fileId = id.slice('/__resolved__virtual:md:'.length)
418
+ const file = ctx.markdownFiles.find(f => f.id === fileId)
419
+ if (!file) {
420
+ throw new Error(`Markdown file not found: ${fileId}`)
421
+ }
422
+ const { html, frontmatter, relativePath } = file
423
+ return `export const html = ${JSON.stringify(html)}
424
+ export const frontmatter = ${JSON.stringify(frontmatter)}
425
+ export const relativePath = ${JSON.stringify(relativePath)}
426
+
427
+ if (import.meta.hot) {
428
+ import.meta.hot.accept(newModule => {
429
+ if (newModule) {
430
+ window.__hst_md_hmr(newModule)
431
+ }
432
+ })
433
+ }`
434
+ }
404
435
  },
405
436
 
406
437
  handleHotUpdate (updateContext) {
@@ -411,8 +442,12 @@ if (import.meta.hot) {
411
442
  },
412
443
 
413
444
  configureServer (server) {
445
+ let firstMount = true
414
446
  server.ws.on('histoire:mount', () => {
415
- notifyStoryChange()
447
+ if (!firstMount) {
448
+ notifyStoryChange()
449
+ }
450
+ firstMount = false
416
451
  })
417
452
 
418
453
  server.middlewares.use(async (req, res, next) => {