msw-storybook-addon
Version:
Mock APIs in Storybook using Mock Service Worker.
52 lines (51 loc) • 1.95 kB
JavaScript
import { n as defaultSetup } from "./addon-DN-DOgIS.mjs";
//#region src/csf3.ts
/**
* Resolve the legacy `parameters.msw` handler definitions to a flat list of handlers.
*/
function resolveHandlers(parameter) {
if (Array.isArray(parameter)) return parameter;
if (parameter.handlers == null) return [];
return (Array.isArray(parameter.handlers) ? parameter.handlers : Object.values(parameter.handlers)).flat().filter(Boolean);
}
let hasPrintedDeprecationWarning = false;
function printDeprecationWarning() {
if (!hasPrintedDeprecationWarning) {
console.warn("[msw-storybook-addon] `mswLoader` is deprecated when using CSF Next — use `addonMsw()` instead. Run `npx msw-storybook-migrate` to migrate.\n\nLearn more: https://github.com/mswjs/msw-storybook-addon/blob/main/MIGRATION.md#from-2xx-to-3xx");
hasPrintedDeprecationWarning = true;
}
}
let mswInstancePromise;
/**
* Create a loader to initialize Mock Service Worker. This is the supported
* integration for CSF 3.0 projects.
*
* Deprecated when using CSF Next: use the preview annotations (`addonMsw()`)
* instead. Run `npx msw-storybook-migrate` to migrate automatically. See the
* {@link https://github.com/mswjs/msw-storybook-addon/blob/main/MIGRATION.md#from-2xx-to-3xx migration guide}
* for details.
*
* @example
* // .storybook/preview.ts
* import { mswLoader } from 'msw-storybook-addon/csf3'
*
* export default {
* loaders: [mswLoader()],
* parameters: {
* msw: [...initialHandlers]
* }
* }
*/
function mswLoader(setup = defaultSetup) {
return async (context) => {
if (context.parameters.csfFactory === true) printDeprecationWarning();
const worker = await (mswInstancePromise ??= Promise.resolve(setup()));
context.msw = worker;
worker.resetHandlers();
const handlers = context.parameters.msw ? resolveHandlers(context.parameters.msw) : [];
if (handlers.length !== 0) worker.use(...handlers);
return {};
};
}
//#endregion
export { mswLoader };