Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 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 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 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 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 | 1x 1x 10x 5x 5x 5x 5x 5x 5x 5x 5x 3x | /**
* Reusable Storybook main configuration factory for blong suites.
*
* Provides the common setup (framework, addons, viteFinal) so each
* package only needs to declare its own stories paths and any extra
* realm packages whose stories should be included.
*
* Usage in a suite's .storybook/main.ts:
* ```ts
* import {defineBlongStorybookMain} from '@feasibleone/blong-browser/storybookMain';
* export default defineBlongStorybookMain({
* importMetaDirname: __dirname,
* realmPackages: ['@feasibleone/blong-marine'],
* });
* ```
*
* Usage in a realm's own .storybook/main.ts (standalone):
* ```ts
* import {defineBlongStorybookMain} from '@feasibleone/blong-browser/storybookMain';
* export default defineBlongStorybookMain({importMetaDirname: __dirname});
* ```
*
* Adding another realm to a suite is as simple as appending its package name
* to the `realmPackages` array — the helper resolves story paths automatically.
*/
import type {StorybookConfig} from '@storybook/react-vite';
import {existsSync} from 'node:fs';
import {createRequire} from 'node:module';
import {dirname, resolve} from 'node:path';
import {storybookBackend, storybookBackendDefine} from './storybookBackend.ts';
import {sourceLinkDefine} from './sourceLinkDefine.ts';
/**
* Name of the app-only plugin that stubs a realm's `meta/fixture` modules.
*
* A literal rather than an import of `DROP_FIXTURES` from `./vite.ts`: Storybook
* loads this module as raw ESM, where the app config's `.js`-for-`.ts` imports
* do not resolve. Keep the two in step — the value is asserted against the plugin
* it removes in `storybookMain.test.ts`.
*/
const DROP_FIXTURES = 'blong-drop-fixtures';
export interface IBlongStorybookMainOptions {
/**
* Absolute path of the `.storybook/` directory — pass `__dirname`.
* Used to build the relative story globs and monorepo fs.allow paths.
*/
importMetaDirname: string;
/**
* Additional stories globs relative to the package root (one level up from
* `.storybook/`). Defaults to `['../src/**\/*.stories.@(ts|tsx)']`.
*/
localStories?: string[];
/**
* npm package names whose `src/stories/` (or resolved story paths) should
* be included. The helper resolves each package's location and appends its
* stories to the `stories` array with correct absolute paths.
*
* Adding a realm to a suite:
* ```ts
* realmPackages: ['@feasibleone/blong-marine', '@feasibleone/my-realm'],
* ```
*/
realmPackages?: string[];
/**
* Additional Storybook addons. Merged after the defaults
* (`@storybook/addon-a11y`).
*/
extraAddons?: string[];
}
function getAbsolutePath(value: string, fromDir: string): string {
return dirname(createRequire(fromDir + '/package.json').resolve(`${value}/package.json`));
}
function resolveRealmStories(packageName: string, fromDir: string): string[] {
try {
const pkgPath = createRequire(fromDir + '/package.json').resolve(
`${packageName}/package.json`,
);
const realmRoot = dirname(pkgPath);
return [`${realmRoot}/src/stories/**/*.stories.@(ts|tsx)`];
} catch {
console.warn(`[blong-browser/storybookMain] Could not resolve stories for ${packageName}`);
return [];
}
}
export function defineBlongStorybookMain(options: IBlongStorybookMainOptions): StorybookConfig {
const {
importMetaDirname,
localStories = ['../src/**/*.stories.@(ts|tsx)'],
realmPackages = [],
extraAddons = [],
} = options;
const realmStories = realmPackages.flatMap(pkg => resolveRealmStories(pkg, importMetaDirname));
const monorepoNodeModules = resolve(importMetaDirname, '../../../common/temp/node_modules');
// Extra fs.allow entries for realm story file roots
const realmRoots = realmPackages.flatMap(pkg => {
try {
const pkgPath = createRequire(importMetaDirname + '/package.json').resolve(
`${pkg}/package.json`,
);
return [dirname(pkgPath)];
} catch {
return [];
}
});
// Storybook dev servers reach assets by absolute path (`/@fs/<path>`), and a
// path outside `server.fs.allow` is refused with 403 — which reads as a broken
// theme rather than a config gap. The list cannot be assembled from the
// consumer package alone: a realm's stories import from blong-browser (which
// owns the theme images), and a suite's from any realm it composes, none of
// which is under `<package>/.storybook`. So the monorepo root is allowed
// too — the same reach Vite's own default (the workspace root) would give,
// which setting `allow` at all otherwise discards.
const monorepoRoot = resolve(importMetaDirname, '../../..');
/**
* A package's `public/` folder, served at the root in Storybook.
*
* `vite build` copies it into `dist/` by itself, which is why a brand logo
* named as `import.meta.env.BASE_URL` + `logo.svg` works in the deployed
* app; Storybook has no such default and would answer 404 for the same
* path. Guarded by the existence check because most packages have no
* `public/` and Storybook warns about a static directory that is not there.
*/
const publicDir = resolve(importMetaDirname, '../public');
return {
stories: [...localStories, ...realmStories],
...(existsSync(publicDir) ? {staticDirs: [{from: publicDir, to: '/'}]} : {}),
addons: [
getAbsolutePath('@storybook/addon-a11y', importMetaDirname),
...extraAddons.map(a => getAbsolutePath(a, importMetaDirname)),
],
framework: {
name: getAbsolutePath(
'@storybook/react-vite',
importMetaDirname,
) as '@storybook/react-vite',
options: {},
},
typescript: {
reactDocgen: 'react-docgen-typescript',
},
viteFinal(config) {
return {
...config,
// Storybook is the one build that wants a realm's fixtures: an app
// build stubs every `meta/fixture` module (`defineBlongViteConfig`
// installs the plugin), and Storybook resolves the project's own
// `vite.config.ts` into this one — verified by removing the stub by
// hand and watching the fixture leave the Storybook bundle too.
plugins: (config.plugins ?? [])
.flat()
.filter(plugin => (plugin as {name?: string})?.name !== DROP_FIXTURES)
// The live-backend toolbar: mints a token per role and, in the
// JSON-RPC mode, terminates `/rpc` for the page. Inert in a
// build, where `configureServer` never runs.
.concat(storybookBackend()),
// A realm child is an `async function ui() {…}`, and the loader finds
// that child's config block by the function's own name — a child
// whose name minification dropped is skipped in silence, so a
// built Storybook serves a platform with no `ui` realm: the model
// page stories then die in `getPort('ui.portal')` before they
// render, while the dev server (which keeps the names) is fine.
// `output.keepNames` was tried first and changed nothing on this
// Vite — the bundle came back byte-identical — so names are kept by
// not minifying, which is what the app build does for the same
// reason (`defineBlongViteConfig`) @@F-537.
build: {
...config.build,
minify: false,
},
define: {
...config.define,
'process.env': {},
...storybookBackendDefine(),
...sourceLinkDefine(resolve(importMetaDirname, '..')),
},
resolve: {
...config.resolve,
conditions: ['development', ...(config.resolve?.conditions ?? [])],
dedupe: ['react', 'react-dom'],
},
server: {
...config.server,
fs: {
...config.server?.fs,
allow: [
// Whatever the project's own vite config already allows.
...(config.server?.fs?.allow ?? []),
resolve(importMetaDirname, '..'),
monorepoRoot,
monorepoNodeModules,
...realmRoots,
],
},
},
};
},
};
}
|