poveste 0.8.0 → 0.8.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.
- package/dist/node/bin.js +27 -3
- package/dist/node/build.js +220 -177
- package/dist/node/collect/define-globals.d.ts +1 -0
- package/dist/node/collect/define-globals.js +42 -0
- package/dist/node/collect/index.js +4 -0
- package/dist/node/collect/worker.d.ts +1 -0
- package/dist/node/collect/worker.js +5 -0
- package/dist/node/optimize-entries.d.ts +3 -0
- package/dist/node/optimize-entries.js +48 -0
- package/dist/node/vite.js +4 -0
- package/package.json +5 -5
package/dist/node/bin.js
CHANGED
|
@@ -7,6 +7,30 @@ const { version } = JSON.parse(fs.readFileSync(resolve(__dirname, '../../package
|
|
|
7
7
|
process.env.NODE_ENV = process.argv.includes('build') || process.argv.includes('preview') ? 'production' : 'development';
|
|
8
8
|
process.env.HISTOIRE = 'true';
|
|
9
9
|
process.env.POVESTE = 'true';
|
|
10
|
+
// sade does not await an action, so a rejected command was terminated only by
|
|
11
|
+
// Node's default handling of the unhandled rejection it became. That is not the
|
|
12
|
+
// CLI's to rely on: any dependency can install an `unhandledRejection` listener
|
|
13
|
+
// and take it away, which Vike does — and a failed build then ran forever with
|
|
14
|
+
// its error already printed (#405).
|
|
15
|
+
//
|
|
16
|
+
// So failure is reported and exited here, deliberately. `exitCode` alone is not
|
|
17
|
+
// enough — teardown does not get every handle back, and after a failed build a
|
|
18
|
+
// `Timeout` and three `MessagePort`s are still open, so waiting for an empty
|
|
19
|
+
// event loop is what hung in the first place. But exiting on the same tick as
|
|
20
|
+
// the error would truncate it: writes to a piped stderr are asynchronous, and a
|
|
21
|
+
// framed compiler error is long.
|
|
22
|
+
//
|
|
23
|
+
// So both: the exit code is set immediately, and the hard exit is a timer that
|
|
24
|
+
// does not itself hold the loop open. A process with nothing leaked exits on its
|
|
25
|
+
// own, flushing normally; one that leaked is cut loose a moment later, by which
|
|
26
|
+
// time the error has been written.
|
|
27
|
+
function run(command) {
|
|
28
|
+
return command().then(() => undefined, (error) => {
|
|
29
|
+
console.error(error);
|
|
30
|
+
process.exitCode = 1;
|
|
31
|
+
setTimeout(() => process.exit(1), 500).unref();
|
|
32
|
+
});
|
|
33
|
+
}
|
|
10
34
|
const program = sade('poveste');
|
|
11
35
|
program.version(version);
|
|
12
36
|
program.command('dev')
|
|
@@ -17,14 +41,14 @@ program.command('dev')
|
|
|
17
41
|
.option('--host [host]', '[string] specify hostname (omit value or pass `0.0.0.0` to expose to all network interfaces)')
|
|
18
42
|
.action(async (options) => {
|
|
19
43
|
const { devCommand } = await import('./commands/dev.js');
|
|
20
|
-
return devCommand(options);
|
|
44
|
+
return run(() => devCommand(options));
|
|
21
45
|
});
|
|
22
46
|
program.command('build')
|
|
23
47
|
.describe('build the poveste final app you can deploy')
|
|
24
48
|
.option('-c, --config <file>', `[string] use specified config file`)
|
|
25
49
|
.action(async (options) => {
|
|
26
50
|
const { buildCommand } = await import('./commands/build.js');
|
|
27
|
-
return buildCommand(options);
|
|
51
|
+
return run(() => buildCommand(options));
|
|
28
52
|
});
|
|
29
53
|
program.command('preview')
|
|
30
54
|
.describe('preview the built directory')
|
|
@@ -33,6 +57,6 @@ program.command('preview')
|
|
|
33
57
|
.option('--host [host]', '[string] specify hostname (omit value or pass `0.0.0.0` to expose to all network interfaces)')
|
|
34
58
|
.action(async (options) => {
|
|
35
59
|
const { previewCommand } = await import('./commands/preview.js');
|
|
36
|
-
return previewCommand(options);
|
|
60
|
+
return run(() => previewCommand(options));
|
|
37
61
|
});
|
|
38
62
|
program.parse(process.argv);
|
package/dist/node/build.js
CHANGED
|
@@ -14,6 +14,7 @@ import { startPreview } from './preview.js';
|
|
|
14
14
|
import { findAllStories } from './stories.js';
|
|
15
15
|
import { chromeCssScopePlugin, entryCssMergerPlugin, userCssScopePlugin, } from './style-isolation/index.js';
|
|
16
16
|
import { applyHeadTransform } from './util/head.js';
|
|
17
|
+
import { wrapLogError } from './util/log.js';
|
|
17
18
|
import { getViteConfigWithPlugins } from './vite.js';
|
|
18
19
|
const PRELOAD_MODULES = [
|
|
19
20
|
'vendor',
|
|
@@ -53,195 +54,237 @@ export async function build(ctx) {
|
|
|
53
54
|
optimizeDeps: { include: [], noDiscovery: true },
|
|
54
55
|
}));
|
|
55
56
|
await server.pluginContainer.buildStart({});
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
57
|
+
// Everything from here is wrapped so the server is closed on the way out
|
|
58
|
+
// whichever way that is — it is the other handle that kept a failed build
|
|
59
|
+
// alive (#405). `serverClosed` keeps the existing order rather than moving the
|
|
60
|
+
// buildEnd callbacks either side of the close.
|
|
61
|
+
let serverClosed = false;
|
|
62
|
+
try {
|
|
63
|
+
const moduleLoader = useModuleLoader({
|
|
64
|
+
server,
|
|
65
|
+
throws: true,
|
|
66
|
+
});
|
|
67
|
+
const changeViteConfigCallbacks = [];
|
|
68
|
+
const buildEndCallbacks = [];
|
|
69
|
+
const previewStoryCallbacks = [];
|
|
70
|
+
for (const plugin of ctx.config.plugins) {
|
|
71
|
+
if (plugin.onBuild) {
|
|
72
|
+
const api = new BuildPluginApi(ctx, plugin, moduleLoader);
|
|
73
|
+
await plugin.onBuild(api);
|
|
74
|
+
changeViteConfigCallbacks.push(...api.changeViteConfigCallbacks);
|
|
75
|
+
buildEndCallbacks.push(...api.buildEndCallbacks);
|
|
76
|
+
previewStoryCallbacks.push(...api.previewStoryCallbacks);
|
|
77
|
+
}
|
|
70
78
|
}
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
79
|
+
// Collect story data
|
|
80
|
+
const { executeStoryFile, destroy: destroyCollectStories } = useCollectStories({
|
|
81
|
+
server,
|
|
82
|
+
throws: true,
|
|
83
|
+
}, ctx);
|
|
84
|
+
// `throws: true`, so one bad story rejects here. Without the `finally` the
|
|
85
|
+
// teardown below never ran, eleven worker threads stayed alive, and the process
|
|
86
|
+
// hung instead of failing — the error was printed and then nothing (#405).
|
|
87
|
+
try {
|
|
88
|
+
await Promise.all(ctx.storyFiles.map(storyFile => executeStoryFile(storyFile)));
|
|
89
|
+
}
|
|
90
|
+
finally {
|
|
91
|
+
// Logged, not thrown: a teardown that rejects would replace the error that
|
|
92
|
+
// caused the teardown, which is the failure this whole change is about.
|
|
93
|
+
// Same wrapper the dev path uses for these exact calls (server.ts).
|
|
94
|
+
await wrapLogError('destroyCollectStories', () => destroyCollectStories());
|
|
95
|
+
}
|
|
96
|
+
const storyCount = ctx.storyFiles.reduce((sum, file) => sum + (file.story?.variants.length ? 1 : 0), 0);
|
|
97
|
+
const variantCount = ctx.storyFiles.reduce((sum, file) => sum + (file.story?.variants.length ?? 0), 0);
|
|
98
|
+
const emptyStoryCount = ctx.storyFiles.length - storyCount;
|
|
99
|
+
const { viteConfig: buildViteConfigRaw } = await getViteConfigWithPlugins(false, ctx);
|
|
100
|
+
const buildViteConfig = mergeViteConfig(buildViteConfigRaw, {
|
|
101
|
+
mode: 'development',
|
|
102
|
+
build: {
|
|
103
|
+
lib: false,
|
|
104
|
+
rollupOptions: {
|
|
105
|
+
// Named, not an array. With an array the bundler derives `[name]` from the
|
|
106
|
+
// path, and `APP_PATH` is absolute — so any framework whose `entryFileNames`
|
|
107
|
+
// refuses a path-shaped `[name]` fails the build outright (#369, and
|
|
108
|
+
// histoire-dev/histoire#802 before it). The keys make `[name]` the key.
|
|
109
|
+
input: {
|
|
110
|
+
'bundle-main': join(APP_PATH, 'bundle-main.js'),
|
|
111
|
+
'bundle-sandbox': join(APP_PATH, 'bundle-sandbox.js'),
|
|
100
112
|
},
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
// Nuxt: replaces the Nuxt vite dev server
|
|
109
|
-
buildViteConfig.plugins.push({
|
|
110
|
-
name: 'poveste-vue-plugin-override',
|
|
111
|
-
config(config) {
|
|
112
|
-
const vuePlugin = config.plugins.find((p) => p.name === 'vite:vue');
|
|
113
|
-
if (vuePlugin) {
|
|
114
|
-
// @ts-expect-error vue plugin use function form
|
|
115
|
-
const original = vuePlugin.configureServer.bind(vuePlugin);
|
|
116
|
-
vuePlugin.configureServer = () => {
|
|
117
|
-
original({
|
|
118
|
-
...server,
|
|
119
|
-
config: {
|
|
120
|
-
...server.config,
|
|
121
|
-
server: {
|
|
122
|
-
...server.config.server,
|
|
123
|
-
hmr: false,
|
|
113
|
+
plugins: [
|
|
114
|
+
{
|
|
115
|
+
name: 'poveste-build-rollup-options-override',
|
|
116
|
+
enforce: 'post',
|
|
117
|
+
options(options) {
|
|
118
|
+
// Don't externalize
|
|
119
|
+
options.external = [];
|
|
124
120
|
},
|
|
125
121
|
},
|
|
126
|
-
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
122
|
+
],
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
});
|
|
126
|
+
// For @vite/plugin-vue: Always put our vite server
|
|
127
|
+
// Disable template inlining
|
|
128
|
+
// (so that we no longer need defineExpose)
|
|
129
|
+
// Nuxt: replaces the Nuxt vite dev server
|
|
130
|
+
buildViteConfig.plugins.push({
|
|
131
|
+
name: 'poveste-vue-plugin-override',
|
|
132
|
+
config(config) {
|
|
133
|
+
const vuePlugin = config.plugins.find((p) => p.name === 'vite:vue');
|
|
134
|
+
if (vuePlugin) {
|
|
135
|
+
// @ts-expect-error vue plugin use function form
|
|
136
|
+
const original = vuePlugin.configureServer.bind(vuePlugin);
|
|
137
|
+
vuePlugin.configureServer = () => {
|
|
138
|
+
original({
|
|
139
|
+
...server,
|
|
140
|
+
config: {
|
|
141
|
+
...server.config,
|
|
142
|
+
server: {
|
|
143
|
+
...server.config.server,
|
|
144
|
+
hmr: false,
|
|
145
|
+
},
|
|
146
|
+
},
|
|
147
|
+
});
|
|
148
|
+
};
|
|
149
|
+
// @ts-expect-error vue plugin use function form
|
|
150
|
+
vuePlugin.configureServer(server);
|
|
151
|
+
}
|
|
152
|
+
},
|
|
153
|
+
});
|
|
154
|
+
buildViteConfig.plugins.push({
|
|
155
|
+
name: 'poveste-build-config-override',
|
|
156
|
+
enforce: 'post',
|
|
157
|
+
config(config) {
|
|
158
|
+
// Don't externalize
|
|
159
|
+
config.build.rollupOptions.external = [];
|
|
160
|
+
// Force chunk strategy
|
|
161
|
+
config.build.rollupOptions.output = {
|
|
162
|
+
manualChunks(id) {
|
|
163
|
+
// Vite's runtime helpers (`\0vite/preload-helper.js` and friends) are
|
|
164
|
+
// virtual modules, so the node_modules routing below never sees them
|
|
165
|
+
// and their placement is left to the bundler — which parked
|
|
166
|
+
// `__vitePreload` inside the 10 MB `highlighter` chunk. Every chunk
|
|
167
|
+
// importing the helper then statically imported the whole highlighter,
|
|
168
|
+
// and the sandbox was back to evaluating it once per grid cell (#197),
|
|
169
|
+
// undoing exactly what `APP_ONLY_VENDORS` is for. Pin them somewhere
|
|
170
|
+
// harmless instead of leaving the choice to chunking heuristics.
|
|
171
|
+
if (id.replace(/^\0/, '').startsWith('vite/')) {
|
|
172
|
+
return 'app-runtime';
|
|
156
173
|
}
|
|
157
|
-
|
|
158
|
-
if (
|
|
159
|
-
|
|
160
|
-
|
|
174
|
+
if (!id.includes('@poveste/app') && id.includes('node_modules')) {
|
|
175
|
+
if (APP_ONLY_VENDORS.some(test => test.test(id))) {
|
|
176
|
+
return 'highlighter';
|
|
177
|
+
}
|
|
178
|
+
for (const test of ctx.config.build?.excludeFromVendorsChunk ?? []) {
|
|
179
|
+
if ((typeof test === 'string' && id.includes(test)) || (test instanceof RegExp && test.test(id))) {
|
|
180
|
+
// Excluded from vendor chunk
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
161
183
|
}
|
|
184
|
+
return 'vendor';
|
|
185
|
+
}
|
|
186
|
+
},
|
|
187
|
+
};
|
|
188
|
+
// A framework that declares Vite environments gives each one its own
|
|
189
|
+
// `build.outDir`, and that wins over the top-level value for the environment's
|
|
190
|
+
// output — so the book was written to the framework's directory (Vike: `dist/client`)
|
|
191
|
+
// while poveste kept looking in `outDir` (#369). Only the client environment
|
|
192
|
+
// builds the book. Where no framework declared environments there is nothing to
|
|
193
|
+
// override, and where one did this puts the book back where poveste reads it.
|
|
194
|
+
if (config.environments?.client?.build) {
|
|
195
|
+
config.environments.client.build.outDir = ctx.config.outDir;
|
|
196
|
+
}
|
|
197
|
+
// Force vite build options
|
|
198
|
+
Object.assign(config.build, {
|
|
199
|
+
outDir: ctx.config.outDir,
|
|
200
|
+
emptyOutDir: true,
|
|
201
|
+
// Re-merged per-entry by entry-css-merger.
|
|
202
|
+
cssCodeSplit: true,
|
|
203
|
+
minify: false,
|
|
204
|
+
// Don't build in SSR mode
|
|
205
|
+
ssr: false,
|
|
206
|
+
});
|
|
207
|
+
config.define.__HST_COLLECT__ = false;
|
|
208
|
+
},
|
|
209
|
+
});
|
|
210
|
+
const isolate = ctx.config.isolateStyles !== false;
|
|
211
|
+
buildViteConfig.plugins.push(userCssScopePlugin({ enabled: isolate }));
|
|
212
|
+
buildViteConfig.plugins.push(chromeCssScopePlugin({ enabled: isolate }));
|
|
213
|
+
buildViteConfig.plugins.push(entryCssMergerPlugin({ isolateStyles: isolate }));
|
|
214
|
+
for (const cb of changeViteConfigCallbacks) {
|
|
215
|
+
console.log('vite config hook', cb);
|
|
216
|
+
await cb(buildViteConfig);
|
|
217
|
+
}
|
|
218
|
+
const results = await viteBuild(buildViteConfig);
|
|
219
|
+
const result = Array.isArray(results) ? results[0] : results;
|
|
220
|
+
function findEntryCss(entryName) {
|
|
221
|
+
return result.output.find(o => o.type === 'asset' && o.fileName === `${entryName}.css`);
|
|
222
|
+
}
|
|
223
|
+
const mainStyleOutput = findEntryCss('bundle-main')
|
|
224
|
+
?? result.output.find(o => o.name === 'style.css' && o.type === 'asset');
|
|
225
|
+
const sandboxStyleOutput = findEntryCss('bundle-sandbox') ?? mainStyleOutput;
|
|
226
|
+
// Preload
|
|
227
|
+
const preloadOutputs = result.output.filter(o => PRELOAD_MODULES.includes(o.name) && o.type === 'chunk');
|
|
228
|
+
const preloadHtml = generateScriptLinks(preloadOutputs.map(o => o.fileName), 'preload', ctx);
|
|
229
|
+
// Prefetch
|
|
230
|
+
const prefetchOutputs = result.output.filter(o => PREFETCHED_MODULES.includes(o.name) && o.type === 'chunk');
|
|
231
|
+
const prefetchHtml = generateScriptLinks(prefetchOutputs.map(o => o.fileName), 'prefetch', ctx);
|
|
232
|
+
// Index
|
|
233
|
+
const indexOutput = result.output.find(o => o.name === 'bundle-main' && o.type === 'chunk');
|
|
234
|
+
let indexHtml = generateEntryHtml(indexOutput.fileName, mainStyleOutput.fileName, {
|
|
235
|
+
HEAD: `${preloadHtml}${prefetchHtml}`,
|
|
236
|
+
}, ctx);
|
|
237
|
+
indexHtml = await applyHeadTransform(indexHtml, ctx.config.head);
|
|
238
|
+
await writeFile('index.html', indexHtml, ctx);
|
|
239
|
+
// Sandbox
|
|
240
|
+
const sandboxOutput = result.output.find(o => o.name === 'bundle-sandbox' && o.type === 'chunk');
|
|
241
|
+
let sandboxHtml = generateEntryHtml(sandboxOutput.fileName, sandboxStyleOutput.fileName, {}, ctx);
|
|
242
|
+
sandboxHtml = await applyHeadTransform(sandboxHtml, ctx.config.head);
|
|
243
|
+
await writeFile('__sandbox.html', sandboxHtml, ctx);
|
|
244
|
+
await writeFile('poveste.json', JSON.stringify(getSerializedStoryData(ctx), null, 2), ctx);
|
|
245
|
+
const duration = performance.now() - startTime;
|
|
246
|
+
if (emptyStoryCount) {
|
|
247
|
+
console.warn(pc.yellow(`⚠️ ${emptyStoryCount} empty story file${emptyStoryCount === 1 ? '' : 's'}`));
|
|
248
|
+
}
|
|
249
|
+
console.log(pc.green(`✅ Built ${storyCount} stor${storyCount === 1 ? 'y' : 'ies'} (${variantCount} variant${variantCount === 1 ? '' : 's'}) in ${Math.round(duration / 1000 * 100) / 100}s`));
|
|
250
|
+
// Render
|
|
251
|
+
if (previewStoryCallbacks.length) {
|
|
252
|
+
const { baseUrl, close } = await startPreview({}, ctx);
|
|
253
|
+
try {
|
|
254
|
+
for (const storyFile of ctx.storyFiles) {
|
|
255
|
+
const story = storyFile.story;
|
|
256
|
+
for (const variant of story.variants) {
|
|
257
|
+
const query = new URLSearchParams();
|
|
258
|
+
query.append('storyId', story.id);
|
|
259
|
+
query.append('variantId', variant.id);
|
|
260
|
+
const url = `${baseUrl}__sandbox.html?${query.toString()}`;
|
|
261
|
+
for (const fn of previewStoryCallbacks) {
|
|
262
|
+
await fn({
|
|
263
|
+
file: storyFile.path,
|
|
264
|
+
story,
|
|
265
|
+
variant,
|
|
266
|
+
url,
|
|
267
|
+
});
|
|
162
268
|
}
|
|
163
|
-
return 'vendor';
|
|
164
269
|
}
|
|
165
|
-
},
|
|
166
|
-
};
|
|
167
|
-
// Force vite build options
|
|
168
|
-
Object.assign(config.build, {
|
|
169
|
-
outDir: ctx.config.outDir,
|
|
170
|
-
emptyOutDir: true,
|
|
171
|
-
// Re-merged per-entry by entry-css-merger.
|
|
172
|
-
cssCodeSplit: true,
|
|
173
|
-
minify: false,
|
|
174
|
-
// Don't build in SSR mode
|
|
175
|
-
ssr: false,
|
|
176
|
-
});
|
|
177
|
-
config.define.__HST_COLLECT__ = false;
|
|
178
|
-
},
|
|
179
|
-
});
|
|
180
|
-
const isolate = ctx.config.isolateStyles !== false;
|
|
181
|
-
buildViteConfig.plugins.push(userCssScopePlugin({ enabled: isolate }));
|
|
182
|
-
buildViteConfig.plugins.push(chromeCssScopePlugin({ enabled: isolate }));
|
|
183
|
-
buildViteConfig.plugins.push(entryCssMergerPlugin({ isolateStyles: isolate }));
|
|
184
|
-
for (const cb of changeViteConfigCallbacks) {
|
|
185
|
-
console.log('vite config hook', cb);
|
|
186
|
-
await cb(buildViteConfig);
|
|
187
|
-
}
|
|
188
|
-
const results = await viteBuild(buildViteConfig);
|
|
189
|
-
const result = Array.isArray(results) ? results[0] : results;
|
|
190
|
-
function findEntryCss(entryName) {
|
|
191
|
-
return result.output.find(o => o.type === 'asset' && o.fileName === `${entryName}.css`);
|
|
192
|
-
}
|
|
193
|
-
const mainStyleOutput = findEntryCss('bundle-main')
|
|
194
|
-
?? result.output.find(o => o.name === 'style.css' && o.type === 'asset');
|
|
195
|
-
const sandboxStyleOutput = findEntryCss('bundle-sandbox') ?? mainStyleOutput;
|
|
196
|
-
// Preload
|
|
197
|
-
const preloadOutputs = result.output.filter(o => PRELOAD_MODULES.includes(o.name) && o.type === 'chunk');
|
|
198
|
-
const preloadHtml = generateScriptLinks(preloadOutputs.map(o => o.fileName), 'preload', ctx);
|
|
199
|
-
// Prefetch
|
|
200
|
-
const prefetchOutputs = result.output.filter(o => PREFETCHED_MODULES.includes(o.name) && o.type === 'chunk');
|
|
201
|
-
const prefetchHtml = generateScriptLinks(prefetchOutputs.map(o => o.fileName), 'prefetch', ctx);
|
|
202
|
-
// Index
|
|
203
|
-
const indexOutput = result.output.find(o => o.name === 'bundle-main' && o.type === 'chunk');
|
|
204
|
-
let indexHtml = generateEntryHtml(indexOutput.fileName, mainStyleOutput.fileName, {
|
|
205
|
-
HEAD: `${preloadHtml}${prefetchHtml}`,
|
|
206
|
-
}, ctx);
|
|
207
|
-
indexHtml = await applyHeadTransform(indexHtml, ctx.config.head);
|
|
208
|
-
await writeFile('index.html', indexHtml, ctx);
|
|
209
|
-
// Sandbox
|
|
210
|
-
const sandboxOutput = result.output.find(o => o.name === 'bundle-sandbox' && o.type === 'chunk');
|
|
211
|
-
let sandboxHtml = generateEntryHtml(sandboxOutput.fileName, sandboxStyleOutput.fileName, {}, ctx);
|
|
212
|
-
sandboxHtml = await applyHeadTransform(sandboxHtml, ctx.config.head);
|
|
213
|
-
await writeFile('__sandbox.html', sandboxHtml, ctx);
|
|
214
|
-
await writeFile('poveste.json', JSON.stringify(getSerializedStoryData(ctx), null, 2), ctx);
|
|
215
|
-
const duration = performance.now() - startTime;
|
|
216
|
-
if (emptyStoryCount) {
|
|
217
|
-
console.warn(pc.yellow(`⚠️ ${emptyStoryCount} empty story file${emptyStoryCount === 1 ? '' : 's'}`));
|
|
218
|
-
}
|
|
219
|
-
console.log(pc.green(`✅ Built ${storyCount} stor${storyCount === 1 ? 'y' : 'ies'} (${variantCount} variant${variantCount === 1 ? '' : 's'}) in ${Math.round(duration / 1000 * 100) / 100}s`));
|
|
220
|
-
// Render
|
|
221
|
-
if (previewStoryCallbacks.length) {
|
|
222
|
-
const { baseUrl, close } = await startPreview({}, ctx);
|
|
223
|
-
for (const storyFile of ctx.storyFiles) {
|
|
224
|
-
const story = storyFile.story;
|
|
225
|
-
for (const variant of story.variants) {
|
|
226
|
-
const query = new URLSearchParams();
|
|
227
|
-
query.append('storyId', story.id);
|
|
228
|
-
query.append('variantId', variant.id);
|
|
229
|
-
const url = `${baseUrl}__sandbox.html?${query.toString()}`;
|
|
230
|
-
for (const fn of previewStoryCallbacks) {
|
|
231
|
-
await fn({
|
|
232
|
-
file: storyFile.path,
|
|
233
|
-
story,
|
|
234
|
-
variant,
|
|
235
|
-
url,
|
|
236
|
-
});
|
|
237
270
|
}
|
|
238
271
|
}
|
|
272
|
+
finally {
|
|
273
|
+
// A screenshot or percy callback that throws would otherwise leave this
|
|
274
|
+
// server bound — the same leak as the two above, one level down.
|
|
275
|
+
await wrapLogError('startPreview.close', () => close());
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
await server.close();
|
|
279
|
+
serverClosed = true;
|
|
280
|
+
for (const fn of buildEndCallbacks) {
|
|
281
|
+
await fn();
|
|
239
282
|
}
|
|
240
|
-
await close();
|
|
241
283
|
}
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
284
|
+
finally {
|
|
285
|
+
if (!serverClosed) {
|
|
286
|
+
await wrapLogError('server.close', () => server.close());
|
|
287
|
+
}
|
|
245
288
|
}
|
|
246
289
|
}
|
|
247
290
|
function generateBaseHtml(head, body, ctx) {
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function globalsFromDefine(define: Record<string, unknown> | undefined): Record<string, unknown>;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Story collection runs in a Node worker. Externalised dependencies are loaded by
|
|
2
|
+
// native Node ESM, so Vite never applies `define` to them — and a bare compile-time
|
|
3
|
+
// feature flag is just an undefined identifier there. vue-i18n reading
|
|
4
|
+
// `__VUE_PROD_DEVTOOLS__` was the reported case (#284); anything with build-time
|
|
5
|
+
// flags fails the same way.
|
|
6
|
+
//
|
|
7
|
+
// The fix is to give the collection environment the same values a real build would
|
|
8
|
+
// substitute, taken from Vite's own resolved `define` rather than a list of library
|
|
9
|
+
// names this package would have to keep current.
|
|
10
|
+
// Only `__FLAG__`-shaped keys are seeded. Every flag this exists for follows that
|
|
11
|
+
// convention — `__VUE_OPTIONS_API__`, `__VUE_PROD_DEVTOOLS__`, `__VUE_I18N_LEGACY_API__`,
|
|
12
|
+
// `__INTLIFY_PROD_DEVTOOLS__` — and narrow is the right failure here. A browser-targeted
|
|
13
|
+
// config shimming a Node global (`define: { process: '{"env":{}}' }` is a real shape)
|
|
14
|
+
// would otherwise replace the collection worker's own `process`, surfacing far from the
|
|
15
|
+
// config that caused it. Refusing to evaluate arbitrary expressions while letting
|
|
16
|
+
// arbitrary identifiers overwrite the runtime would be a guard in name only.
|
|
17
|
+
// `process.env.NODE_ENV` and friends fail the same test, being member expressions.
|
|
18
|
+
const FEATURE_FLAG = /^__[A-Z0-9_]+__$/;
|
|
19
|
+
// Vite `define` values are JS expression *source*. A plugin-injected flag arrives
|
|
20
|
+
// already parsed (`false`), while a user's `define: { X: 'false' }` arrives as the
|
|
21
|
+
// string `"false"` — and seeding that string would make the flag *truthy*, silently
|
|
22
|
+
// inverting it. So strings are parsed as literals, and anything that is not a literal
|
|
23
|
+
// is skipped: evaluating arbitrary expressions here is not something this should do.
|
|
24
|
+
export function globalsFromDefine(define) {
|
|
25
|
+
const globals = {};
|
|
26
|
+
for (const [key, value] of Object.entries(define ?? {})) {
|
|
27
|
+
if (!FEATURE_FLAG.test(key)) {
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
if (typeof value !== 'string') {
|
|
31
|
+
globals[key] = value;
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
try {
|
|
35
|
+
globals[key] = JSON.parse(value);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
// Not a literal — leave it undefined rather than guess at it.
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return globals;
|
|
42
|
+
}
|
|
@@ -8,6 +8,7 @@ import { ViteNodeServer } from 'vite-node/server';
|
|
|
8
8
|
import { TEMP_PATH } from '../alias.js';
|
|
9
9
|
import { createPath } from '../tree.js';
|
|
10
10
|
import { slash } from '../util/fs.js';
|
|
11
|
+
import { globalsFromDefine } from './define-globals.js';
|
|
11
12
|
export function useCollectStories(options, ctx) {
|
|
12
13
|
const { server, mainServer } = options;
|
|
13
14
|
const node = new ViteNodeServer(server, {
|
|
@@ -34,6 +35,8 @@ export function useCollectStories(options, ctx) {
|
|
|
34
35
|
},
|
|
35
36
|
transformMode: ctx.config.viteNodeTransformMode,
|
|
36
37
|
});
|
|
38
|
+
// Same values a real build substitutes, so externalised deps see their flags.
|
|
39
|
+
const defineGlobals = globalsFromDefine(server.config.define);
|
|
37
40
|
const maxThreads = ctx.config.collectMaxThreads ?? cpus().length;
|
|
38
41
|
const threadsCount = ctx.mode === 'dev'
|
|
39
42
|
? Math.max(Math.min(maxThreads, Math.floor(cpus().length / 2)), 1)
|
|
@@ -83,6 +86,7 @@ export function useCollectStories(options, ctx) {
|
|
|
83
86
|
base: server.config.base,
|
|
84
87
|
storyFile,
|
|
85
88
|
port: workerPort,
|
|
89
|
+
defineGlobals,
|
|
86
90
|
};
|
|
87
91
|
const { storyData } = await threadPool.run(payload, {
|
|
88
92
|
transferList: [
|
|
@@ -22,6 +22,11 @@ parentPort.on('message', (message) => {
|
|
|
22
22
|
export default async (payload) => {
|
|
23
23
|
const startTime = performance.now();
|
|
24
24
|
process.env.HST_COLLECT = 'true';
|
|
25
|
+
// Before any module runs: an externalised dep reads these at import time.
|
|
26
|
+
for (const [key, value] of Object.entries(payload.defineGlobals ?? {})) {
|
|
27
|
+
;
|
|
28
|
+
globalThis[key] = value;
|
|
29
|
+
}
|
|
25
30
|
_rpc = createBirpc({}, {
|
|
26
31
|
post: data => payload.port.postMessage(data),
|
|
27
32
|
on: data => payload.port.on('message', data),
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { PovesteConfig } from '@poveste/shared';
|
|
2
|
+
export declare function optimizeEntries(config: Pick<PovesteConfig, 'storyMatch' | 'storyIgnored' | 'setupFile'>, root: string, isServer: boolean): string[];
|
|
3
|
+
export declare function setupFileEntry(setupFile: PovesteConfig['setupFile'], isServer: boolean): string | undefined;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { globbySync } from 'globby';
|
|
2
|
+
import { resolve } from 'pathe';
|
|
3
|
+
// Vite pre-bundles whatever its dependency scanner reaches by crawling
|
|
4
|
+
// `optimizeDeps.entries`. Two things in a book route around that scan:
|
|
5
|
+
//
|
|
6
|
+
// - stories are loaded dynamically, never statically imported from the app entry
|
|
7
|
+
// - the setup file is reached through `virtual:$poveste-setup`, an id the scanner
|
|
8
|
+
// cannot resolve
|
|
9
|
+
//
|
|
10
|
+
// So a dependency used only in a story or a setup file is discovered on first
|
|
11
|
+
// navigation instead, and Vite answers with `optimized dependencies changed.
|
|
12
|
+
// reloading` — a full reload that drops the preview's scroll and state (#282).
|
|
13
|
+
//
|
|
14
|
+
// The stories are resolved here rather than handed over as patterns, because
|
|
15
|
+
// `storyIgnored` cannot be expressed as entry patterns. Vite globs the whole entries
|
|
16
|
+
// array together, so a `!**/dist/**` negation would also match `APP_PATH`, which *is*
|
|
17
|
+
// `<poveste-app>/dist` — silently dropping the app's own scan entries. Resolving the
|
|
18
|
+
// files gives `storyIgnored` its exact meaning and cannot touch anything else.
|
|
19
|
+
export function optimizeEntries(config, root, isServer) {
|
|
20
|
+
// Same call the collector makes, so the scanner sees exactly the story set the
|
|
21
|
+
// book will load — no stale `dist/` copies the book itself excludes.
|
|
22
|
+
const stories = globbySync(config.storyMatch, {
|
|
23
|
+
cwd: root,
|
|
24
|
+
ignore: config.storyIgnored,
|
|
25
|
+
absolute: true,
|
|
26
|
+
});
|
|
27
|
+
const setup = setupFileEntry(config.setupFile, isServer);
|
|
28
|
+
return setup ? [...stories, resolve(root, setup)] : stories;
|
|
29
|
+
}
|
|
30
|
+
// Mirrors how `virtual/vite-plugin.ts` picks the file. These are documented
|
|
31
|
+
// root-relative and written with a leading slash (`/src/setup.ts`), which
|
|
32
|
+
// `resolve` would read as absolute.
|
|
33
|
+
export function setupFileEntry(setupFile, isServer) {
|
|
34
|
+
if (!setupFile) {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
let file;
|
|
38
|
+
if (typeof setupFile === 'string') {
|
|
39
|
+
file = setupFile;
|
|
40
|
+
}
|
|
41
|
+
else if (isServer && 'server' in setupFile) {
|
|
42
|
+
file = setupFile.server;
|
|
43
|
+
}
|
|
44
|
+
else if (!isServer && 'browser' in setupFile) {
|
|
45
|
+
file = setupFile.browser;
|
|
46
|
+
}
|
|
47
|
+
return file ? file.replace(/^\/+/, '') : undefined;
|
|
48
|
+
}
|
package/dist/node/vite.js
CHANGED
|
@@ -5,6 +5,7 @@ import { dirname, join, relative } from 'pathe';
|
|
|
5
5
|
import { loadConfigFromFile as loadViteConfigFromFile, mergeConfig as mergeViteConfig, searchForWorkspaceRoot, } from 'vite';
|
|
6
6
|
import { APP_PATH, TEMP_PATH } from './alias.js';
|
|
7
7
|
import { createMarkdownPlugins } from './markdown.js';
|
|
8
|
+
import { optimizeEntries } from './optimize-entries.js';
|
|
8
9
|
import { notifyStoryChange } from './stories.js';
|
|
9
10
|
import { chromeCssScopePlugin, globalStylesPlugin, userCssScopePlugin, } from './style-isolation/index.js';
|
|
10
11
|
import { applyHeadTransform } from './util/head.js';
|
|
@@ -124,6 +125,9 @@ export async function getViteConfigWithPlugins(isServer, ctx) {
|
|
|
124
125
|
entries: [
|
|
125
126
|
`${APP_PATH}/bundle-main.js`,
|
|
126
127
|
`${APP_PATH}/bundle-sandbox.js`,
|
|
128
|
+
// Without these the scanner never sees a story or the setup file, and
|
|
129
|
+
// their deps cost a full reload when they turn up later (#282).
|
|
130
|
+
...optimizeEntries(ctx.config, ctx.root, isServer),
|
|
127
131
|
],
|
|
128
132
|
include: optimizeDeps([
|
|
129
133
|
'shiki',
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "poveste",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.8.
|
|
4
|
+
"version": "0.8.2",
|
|
5
5
|
"description": "Interactive component playgrounds for Vue, Svelte and Nuxt — a maintained, drop-in successor to histoire",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "Sorin Gitlan"
|
|
@@ -98,10 +98,10 @@
|
|
|
98
98
|
"sirv": "^3.0.0",
|
|
99
99
|
"unhead": "^3.1.0",
|
|
100
100
|
"vite-node": "^6.0.0",
|
|
101
|
-
"@poveste/
|
|
102
|
-
"@poveste/
|
|
103
|
-
"@poveste/shared": "^0.8.
|
|
104
|
-
"@poveste/vendors": "^0.8.
|
|
101
|
+
"@poveste/app": "^0.8.2",
|
|
102
|
+
"@poveste/controls": "^0.8.2",
|
|
103
|
+
"@poveste/shared": "^0.8.2",
|
|
104
|
+
"@poveste/vendors": "^0.8.2"
|
|
105
105
|
},
|
|
106
106
|
"devDependencies": {
|
|
107
107
|
"@types/fs-extra": "^11.0.4",
|