@canonical/storybook-addon-msw 0.44.1 → 0.47.0
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/README.md +16 -2
- package/dist/esm/lib/worker/createStoryRegistry.js +94 -0
- package/dist/esm/lib/worker/createStoryRegistry.js.map +1 -0
- package/dist/esm/lib/worker/index.js +2 -0
- package/dist/esm/lib/worker/index.js.map +1 -0
- package/dist/esm/lib/worker/startWorker.js +47 -0
- package/dist/esm/lib/worker/startWorker.js.map +1 -0
- package/dist/esm/preview.js +9 -8
- package/dist/esm/preview.js.map +1 -1
- package/dist/types/lib/worker/createStoryRegistry.d.ts +31 -0
- package/dist/types/lib/worker/createStoryRegistry.d.ts.map +1 -0
- package/dist/types/lib/worker/index.d.ts +2 -0
- package/dist/types/lib/worker/index.d.ts.map +1 -0
- package/dist/types/lib/worker/startWorker.d.ts +12 -0
- package/dist/types/lib/worker/startWorker.d.ts.map +1 -0
- package/dist/types/preview.d.ts +11 -13
- package/dist/types/preview.d.ts.map +1 -1
- package/package.json +15 -9
- package/public/mockServiceWorker.js +204 -93
- package/dist/esm/withMSW.js +0 -86
- package/dist/esm/withMSW.js.map +0 -1
- package/dist/types/withMSW.d.ts +0 -16
- package/dist/types/withMSW.d.ts.map +0 -1
package/README.md
CHANGED
|
@@ -96,6 +96,20 @@ export const Loading: Story = {
|
|
|
96
96
|
|
|
97
97
|
The addon adds a toolbar button to toggle MSW globally. When enabled (default), all handlers defined in story parameters intercept matching requests. Disable MSW to test how components behave when API requests reach actual endpoints.
|
|
98
98
|
|
|
99
|
+
## Stories on One Page
|
|
100
|
+
|
|
101
|
+
One worker serves every story shown on a page, from before its loaders run until it is torn down. Where two stories answer one route, the story rendered last wins: give each its own path, or render one in its own iframe with `parameters.docs.story: { inline: false, iframeHeight }`.
|
|
102
|
+
|
|
103
|
+
A story opts out with `parameters.msw.disable`. On its own canvas its requests reach the network; on a docs page, the other stories' handlers can still answer them.
|
|
104
|
+
|
|
105
|
+
```typescript
|
|
106
|
+
export const AgainstTheNetwork: Story = {
|
|
107
|
+
parameters: {
|
|
108
|
+
msw: { disable: true },
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
```
|
|
112
|
+
|
|
99
113
|
## Panel
|
|
100
114
|
|
|
101
115
|
The MSW panel in the addon bar shows which handlers are active for the current story. Use this to verify your handlers are correctly registered and to debug request matching issues.
|
|
@@ -133,7 +147,7 @@ http.get("/api/search", ({ request }) => {
|
|
|
133
147
|
|
|
134
148
|
### Requests not being intercepted
|
|
135
149
|
|
|
136
|
-
Verify the service worker is loaded in DevTools under Application > Service Workers. If missing, re-run `npx msw init public/` and restart Storybook.
|
|
150
|
+
Verify the service worker is loaded in DevTools under Application > Service Workers. The addon registers `./mockServiceWorker.js`, beside the preview's page. If missing, re-run `npx msw init public/` and restart Storybook. On a page without service workers, MSW intercepts requests inside the page instead. In Node, as in vitest's jsdom, the addon starts no worker: serve the handlers with `setupServer` from `msw/node`.
|
|
137
151
|
|
|
138
152
|
Check that request URLs in handlers match exactly, including any leading slashes and query parameters.
|
|
139
153
|
|
|
@@ -143,7 +157,7 @@ Ensure both `msw` and the addon are installed. The `http` and `HttpResponse` imp
|
|
|
143
157
|
|
|
144
158
|
### Handlers work in one story but not another
|
|
145
159
|
|
|
146
|
-
|
|
160
|
+
A story's own `parameters.msw.handlers` replace its meta's. Define common handlers at the meta level if they should apply to all stories in a file:
|
|
147
161
|
|
|
148
162
|
```typescript
|
|
149
163
|
const meta: Meta<typeof Component> = {
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { KEY, PARAM_KEY } from "../../constants.js";
|
|
2
|
+
import startWorker from "./startWorker.js";
|
|
3
|
+
/** Whether MSW serves a story: unless the toolbar or `disable` turns it off. */
|
|
4
|
+
const isActive = (enabled, parameter) => enabled !== false && !(parameter?.disable ?? false);
|
|
5
|
+
/**
|
|
6
|
+
* Create the registry that serves every shown story's
|
|
7
|
+
* `parameters.msw.handlers` together, the story served last first.
|
|
8
|
+
*
|
|
9
|
+
* `import { createStoryRegistry } from "./lib/worker/index.js";`
|
|
10
|
+
*
|
|
11
|
+
* @param start - Starts the worker, or resolves null where none starts.
|
|
12
|
+
* @returns The loader that serves a story, and the beforeEach whose cleanup
|
|
13
|
+
* withdraws it.
|
|
14
|
+
*/
|
|
15
|
+
export default function createStoryRegistry(start = startWorker) {
|
|
16
|
+
const shown = new Map();
|
|
17
|
+
const disarms = new WeakMap();
|
|
18
|
+
let serving = null;
|
|
19
|
+
/** List every shown story's handlers, the story served last first. */
|
|
20
|
+
const listShownHandlers = () => [...shown.values()].reverse().flat();
|
|
21
|
+
/** Whether any of `handlers` is no longer among the shown stories'. */
|
|
22
|
+
const isAnyLeaving = (handlers) => {
|
|
23
|
+
const kept = new Set(listShownHandlers());
|
|
24
|
+
return handlers.some((handler) => !kept.has(handler));
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Serve the shown stories' handlers again, from msw's empty initial list.
|
|
28
|
+
*
|
|
29
|
+
* @note Impure: replaces the worker's handlers.
|
|
30
|
+
*/
|
|
31
|
+
const rebuildServed = () => {
|
|
32
|
+
serving?.resetHandlers();
|
|
33
|
+
serving?.use(...listShownHandlers());
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Withdraw a story, and serve the rest.
|
|
37
|
+
*
|
|
38
|
+
* @note Impure: removes the story from the registry.
|
|
39
|
+
*/
|
|
40
|
+
const withdrawStory = (id) => {
|
|
41
|
+
const withdrawn = shown.get(id);
|
|
42
|
+
shown.delete(id);
|
|
43
|
+
if (withdrawn !== undefined && isAnyLeaving(withdrawn)) {
|
|
44
|
+
rebuildServed();
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* Serve a story's handlers first, adding them alone unless some leave.
|
|
49
|
+
*
|
|
50
|
+
* @note Impure: registers the story and changes the worker's handlers.
|
|
51
|
+
*/
|
|
52
|
+
const serveOn = (worker, id, handlers) => {
|
|
53
|
+
const previous = shown.get(id) ?? [];
|
|
54
|
+
shown.delete(id);
|
|
55
|
+
shown.set(id, handlers);
|
|
56
|
+
if (worker !== null && worker !== serving) {
|
|
57
|
+
serving = worker;
|
|
58
|
+
rebuildServed();
|
|
59
|
+
}
|
|
60
|
+
else if (isAnyLeaving(previous)) {
|
|
61
|
+
rebuildServed();
|
|
62
|
+
}
|
|
63
|
+
else {
|
|
64
|
+
serving?.use(...handlers);
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
return {
|
|
68
|
+
serveStory: async ({ id, globals, parameters, abortSignal }) => {
|
|
69
|
+
const parameter = Reflect.get(parameters, PARAM_KEY);
|
|
70
|
+
if (!isActive(Reflect.get(globals, KEY), parameter)) {
|
|
71
|
+
withdrawStory(id);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
const worker = await start();
|
|
75
|
+
if (abortSignal.aborted) {
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
serveOn(worker, id, parameter?.handlers ?? []);
|
|
79
|
+
disarms.get(abortSignal)?.abort();
|
|
80
|
+
const disarm = new AbortController();
|
|
81
|
+
disarms.set(abortSignal, disarm);
|
|
82
|
+
abortSignal.addEventListener("abort", () => withdrawStory(id), {
|
|
83
|
+
once: true,
|
|
84
|
+
signal: disarm.signal,
|
|
85
|
+
});
|
|
86
|
+
},
|
|
87
|
+
scheduleWithdrawal: ({ id, abortSignal }) => {
|
|
88
|
+
disarms.get(abortSignal)?.abort();
|
|
89
|
+
disarms.delete(abortSignal);
|
|
90
|
+
return () => withdrawStory(id);
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
//# sourceMappingURL=createStoryRegistry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createStoryRegistry.js","sourceRoot":"","sources":["../../../../src/lib/worker/createStoryRegistry.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,M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I,EAAE,CAAC,CAAC;YAC/C,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,CAAC;YAClC,MAAM,MAAM,GAAG,IAAI,eAAe,EAAE,CAAC;YACrC,OAAO,CAAC,GAAG,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;YACjC,WAAW,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,aAAa,CAAC,EAAE,CAAC,EAAE;gBAC7D,IAAI,EAAE,IAAI;gBACV,MAAM,EAAE,MAAM,CAAC,MAAM;aACtB,CAAC,CAAC;QACL,CAAC;QACD,kBAAkB,EAAE,CAAC,EAAE,EAAE,EAAE,WAAW,EAAE,EAAE,EAAE;YAC1C,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,CAAC;YAClC,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;YAC5B,OAAO,GAAG,EAAE,CAAC,aAAa,CAAC,EAAE,CAAC,CAAC;QACjC,CAAC;KACF,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/lib/worker/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,mBAAmB,EAAE,MAAM,0BAA0B,CAAC"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** The preview's one start of the worker, shared by every caller. */
|
|
2
|
+
let starting = null;
|
|
3
|
+
/** Whether this is a Node process, where msw/browser refuses to start. */
|
|
4
|
+
const isNodeProcess = () => {
|
|
5
|
+
const runtime = Reflect.get(globalThis, "process");
|
|
6
|
+
return (Boolean(runtime?.versions?.node) &&
|
|
7
|
+
runtime?.type !== "renderer" &&
|
|
8
|
+
runtime?.type !== "worker");
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* Set up the worker and start it, or warn and resolve null.
|
|
12
|
+
*
|
|
13
|
+
* @note Impure: starts the worker; a failure clears the shared start.
|
|
14
|
+
*/
|
|
15
|
+
const startOnce = async () => {
|
|
16
|
+
try {
|
|
17
|
+
const { setupWorker } = await import("msw/browser");
|
|
18
|
+
const worker = setupWorker();
|
|
19
|
+
await worker.start({
|
|
20
|
+
serviceWorker: { url: "./mockServiceWorker.js" },
|
|
21
|
+
onUnhandledFrame: "bypass",
|
|
22
|
+
});
|
|
23
|
+
return worker;
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
console.warn("[MSW Addon] Failed to start the worker:", error);
|
|
27
|
+
starting = null;
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Start the preview's one worker from `./mockServiceWorker.js`, or resolve
|
|
33
|
+
* null in Node; a failed start warns, and the next call retries.
|
|
34
|
+
*
|
|
35
|
+
* `import startWorker from "./startWorker.js";`
|
|
36
|
+
*
|
|
37
|
+
* @returns The started worker, or null when none started.
|
|
38
|
+
* @note Impure: starts the preview's worker once.
|
|
39
|
+
*/
|
|
40
|
+
export default function startWorker() {
|
|
41
|
+
if (isNodeProcess()) {
|
|
42
|
+
return Promise.resolve(null);
|
|
43
|
+
}
|
|
44
|
+
starting ??= startOnce();
|
|
45
|
+
return starting;
|
|
46
|
+
}
|
|
47
|
+
//# sourceMappingURL=startWorker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"startWorker.js","sourceRoot":"","sources":["../../../../src/lib/worker/startWorker.ts"],"names":[],"mappings":"AAEA,qEAAqE;AACrE,IAAI,QAAQ,GAAuC,IAAI,CAAC;AAQxD,0EAA0E;AAC1E,MAAM,aAAa,GAAG,GAAY,EAAE;IAClC,MAAM,OAAO,GAAwB,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,SAAS,CAAC,CAAC;IACxE,OAAO,CACL,OAAO,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC;QAChC,OAAO,EAAE,IAAI,KAAK,UAAU;QAC5B,OAAO,EAAE,IAAI,KAAK,QAAQ,CAC3B,CAAC;AACJ,CAAC,CAAC;AAEF;;;;GAIG;AACH,MAAM,SAAS,GAAG,KAAK,IAAiC,EAAE;IACxD,IAAI,CAAC;QACH,MAAM,EAAE,WAAW,EAAE,GAAG,MAAM,MAAM,CAAC,aAAa,CAAC,CAAC;QACpD,MAAM,MAAM,GAAG,WAAW,EAAE,CAAC;QAC7B,MAAM,MAAM,CAAC,KAAK,CAAC;YACjB,aAAa,EAAE,EAAE,GAAG,EAAE,wBAAwB,EAAE;YAChD,gBAAgB,EAAE,QAAQ;SAC3B,CAAC,CAAC;QACH,OAAO,MAAM,CAAC;IAChB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,yCAAyC,EAAE,KAAK,CAAC,CAAC;QAC/D,QAAQ,GAAG,IAAI,CAAC;QAChB,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,CAAC,OAAO,UAAU,WAAW;IACjC,IAAI,aAAa,EAAE,EAAE,CAAC;QACpB,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;IACD,QAAQ,KAAK,SAAS,EAAE,CAAC;IACzB,OAAO,QAAQ,CAAC;AAClB,CAAC"}
|
package/dist/esm/preview.js
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
import { KEY } from "./constants.js";
|
|
2
|
-
import {
|
|
2
|
+
import { createStoryRegistry } from "./lib/worker/index.js";
|
|
3
|
+
const registry = createStoryRegistry();
|
|
3
4
|
/**
|
|
4
|
-
*
|
|
5
|
-
*
|
|
5
|
+
* The addon's preview annotations: MSW on by default, and each story's
|
|
6
|
+
* handlers served before its own loaders run, until it is torn down.
|
|
7
|
+
*
|
|
8
|
+
* `import preview from "@canonical/storybook-addon-msw/preview";`
|
|
6
9
|
*/
|
|
7
10
|
const preview = {
|
|
8
|
-
loaders: [
|
|
9
|
-
|
|
10
|
-
initialGlobals: {
|
|
11
|
-
[KEY]: true,
|
|
12
|
-
},
|
|
11
|
+
loaders: [registry.serveStory],
|
|
12
|
+
beforeEach: [registry.scheduleWithdrawal],
|
|
13
|
+
initialGlobals: { [KEY]: true },
|
|
13
14
|
};
|
|
14
15
|
export default preview;
|
|
15
16
|
//# sourceMappingURL=preview.js.map
|
package/dist/esm/preview.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"preview.js","sourceRoot":"","sources":["../../src/preview.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"preview.js","sourceRoot":"","sources":["../../src/preview.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAC;AACrC,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE5D,MAAM,QAAQ,GAAG,mBAAmB,EAAE,CAAC;AAEvC;;;;;GAKG;AACH,MAAM,OAAO,GAAG;IACd,OAAO,EAAE,CAAC,QAAQ,CAAC,UAAU,CAAC;IAC9B,UAAU,EAAE,CAAC,QAAQ,CAAC,kBAAkB,CAAC;IACzC,cAAc,EAAE,EAAE,CAAC,GAAG,CAAC,EAAE,IAAI,EAAE;CACO,CAAC;AAEzC,eAAe,OAAO,CAAC"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { SetupWorker } from "msw/browser";
|
|
2
|
+
import type { BeforeEach, LoaderFunction, Renderer } from "storybook/internal/types";
|
|
3
|
+
/** The annotations that serve the shown stories' handlers. */
|
|
4
|
+
type StoryRegistry = {
|
|
5
|
+
/**
|
|
6
|
+
* A project loader serving the story beside every other shown story,
|
|
7
|
+
* withdrawing it if its render is aborted before its beforeEach.
|
|
8
|
+
*
|
|
9
|
+
* @note Impure: registers the story and changes the worker's handlers.
|
|
10
|
+
*/
|
|
11
|
+
readonly serveStory: LoaderFunction<Renderer>;
|
|
12
|
+
/**
|
|
13
|
+
* A beforeEach whose cleanup withdraws the story.
|
|
14
|
+
*
|
|
15
|
+
* @note Impure: stops the render's abort from withdrawing the story.
|
|
16
|
+
*/
|
|
17
|
+
readonly scheduleWithdrawal: BeforeEach<Renderer>;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Create the registry that serves every shown story's
|
|
21
|
+
* `parameters.msw.handlers` together, the story served last first.
|
|
22
|
+
*
|
|
23
|
+
* `import { createStoryRegistry } from "./lib/worker/index.js";`
|
|
24
|
+
*
|
|
25
|
+
* @param start - Starts the worker, or resolves null where none starts.
|
|
26
|
+
* @returns The loader that serves a story, and the beforeEach whose cleanup
|
|
27
|
+
* withdraws it.
|
|
28
|
+
*/
|
|
29
|
+
export default function createStoryRegistry(start?: () => Promise<SetupWorker | null>): StoryRegistry;
|
|
30
|
+
export {};
|
|
31
|
+
//# sourceMappingURL=createStoryRegistry.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createStoryRegistry.d.ts","sourceRoot":"","sources":["../../../../src/lib/worker/createStoryRegistry.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,KAAK,EACV,UAAU,EACV,cAAc,EACd,QAAQ,EACT,MAAM,0BAA0B,CAAC;AAKlC,8DAA8D;AAC9D,KAAK,aAAa,GAAG;IACnB;;;;;OAKG;IACH,QAAQ,CAAC,UAAU,EAAE,cAAc,CAAC,QAAQ,CAAC,CAAC;IAC9C;;;;OAIG;IACH,QAAQ,CAAC,kBAAkB,EAAE,UAAU,CAAC,QAAQ,CAAC,CAAC;CACnD,CAAC;AAQF;;;;;;;;;GASG;AACH,MAAM,CAAC,OAAO,UAAU,mBAAmB,CACzC,KAAK,GAAE,MAAM,OAAO,CAAC,WAAW,GAAG,IAAI,CAAe,GACrD,aAAa,CA0Ff"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/lib/worker/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,mBAAmB,EAAE,MAAM,0BAA0B,CAAC"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { SetupWorker } from "msw/browser";
|
|
2
|
+
/**
|
|
3
|
+
* Start the preview's one worker from `./mockServiceWorker.js`, or resolve
|
|
4
|
+
* null in Node; a failed start warns, and the next call retries.
|
|
5
|
+
*
|
|
6
|
+
* `import startWorker from "./startWorker.js";`
|
|
7
|
+
*
|
|
8
|
+
* @returns The started worker, or null when none started.
|
|
9
|
+
* @note Impure: starts the preview's worker once.
|
|
10
|
+
*/
|
|
11
|
+
export default function startWorker(): Promise<SetupWorker | null>;
|
|
12
|
+
//# sourceMappingURL=startWorker.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"startWorker.d.ts","sourceRoot":"","sources":["../../../../src/lib/worker/startWorker.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AA0C/C;;;;;;;;GAQG;AACH,MAAM,CAAC,OAAO,UAAU,WAAW,IAAI,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CAMjE"}
|
package/dist/types/preview.d.ts
CHANGED
|
@@ -1,18 +1,16 @@
|
|
|
1
|
+
import type { Renderer } from "storybook/internal/types";
|
|
1
2
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
* - with extra rendering
|
|
5
|
-
* - gather details about how a story is rendered
|
|
3
|
+
* The addon's preview annotations: MSW on by default, and each story's
|
|
4
|
+
* handlers served before its own loaders run, until it is torn down.
|
|
6
5
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* https://storybook.js.org/docs/react/writing-stories/decorators
|
|
10
|
-
*/
|
|
11
|
-
import type { ProjectAnnotations, Renderer } from "storybook/internal/types";
|
|
12
|
-
/**
|
|
13
|
-
* Note: if you want to use JSX in this file, rename it to `preview.tsx`
|
|
14
|
-
* and update the entry prop in tsup.config.ts to use "src/preview.tsx",
|
|
6
|
+
* `import preview from "@canonical/storybook-addon-msw/preview";`
|
|
15
7
|
*/
|
|
16
|
-
declare const preview:
|
|
8
|
+
declare const preview: {
|
|
9
|
+
loaders: import("storybook/internal/types").LoaderFunction<Renderer>[];
|
|
10
|
+
beforeEach: import("storybook/internal/types").BeforeEach<Renderer>[];
|
|
11
|
+
initialGlobals: {
|
|
12
|
+
"ds-msw-addon": boolean;
|
|
13
|
+
};
|
|
14
|
+
};
|
|
17
15
|
export default preview;
|
|
18
16
|
//# sourceMappingURL=preview.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"preview.d.ts","sourceRoot":"","sources":["../../src/preview.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"preview.d.ts","sourceRoot":"","sources":["../../src/preview.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAsB,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAM7E;;;;;GAKG;AACH,QAAA,MAAM,OAAO;;;;;;CAI2B,CAAC;eAE1B,OAAO"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@canonical/storybook-addon-msw",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.47.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist",
|
|
@@ -47,30 +47,36 @@
|
|
|
47
47
|
"check:biome:fix": "biome check --write",
|
|
48
48
|
"check:ts": "tsc --noEmit",
|
|
49
49
|
"check:webarchitect": "webarchitect library",
|
|
50
|
-
"test": "
|
|
50
|
+
"test": "vitest run",
|
|
51
|
+
"test:watch": "vitest",
|
|
52
|
+
"test:coverage": "vitest run --coverage"
|
|
51
53
|
},
|
|
52
54
|
"dependencies": {
|
|
53
|
-
"@canonical/styles-debug": "^0.
|
|
55
|
+
"@canonical/styles-debug": "^0.47.0",
|
|
54
56
|
"@storybook/icons": "^2.0.1"
|
|
55
57
|
},
|
|
56
58
|
"devDependencies": {
|
|
57
59
|
"@biomejs/biome": "2.5.15",
|
|
58
60
|
"@canonical/biome-config": "0.43.0",
|
|
59
|
-
"@canonical/storybook-config": "^0.
|
|
60
|
-
"@canonical/typescript-config-react": "^0.
|
|
61
|
-
"@canonical/webarchitect": "0.
|
|
61
|
+
"@canonical/storybook-config": "^0.47.0",
|
|
62
|
+
"@canonical/typescript-config-react": "^0.47.0",
|
|
63
|
+
"@canonical/webarchitect": "0.44.0",
|
|
62
64
|
"@storybook/addon-docs": "^10.6.0",
|
|
63
65
|
"@storybook/react-vite": "^10.6.0",
|
|
66
|
+
"@testing-library/react": "^16.3.2",
|
|
64
67
|
"@types/node": "^26.0.0",
|
|
65
68
|
"@types/react": "^19.2.14",
|
|
66
69
|
"@types/react-dom": "^19.2.3",
|
|
67
70
|
"@vitejs/plugin-react": "^6.0.0",
|
|
68
|
-
"
|
|
71
|
+
"@vitest/coverage-v8": "^5.0.0",
|
|
72
|
+
"jsdom": "^28.1.0",
|
|
73
|
+
"msw": "^3.0.0",
|
|
69
74
|
"react": "^19.2.4",
|
|
70
75
|
"react-dom": "^19.2.4",
|
|
71
76
|
"storybook": "^10.6.0",
|
|
72
77
|
"typescript": "^7.0.2",
|
|
73
|
-
"vite": "^8.0.1"
|
|
78
|
+
"vite": "^8.0.1",
|
|
79
|
+
"vitest": "^5.0.0"
|
|
74
80
|
},
|
|
75
81
|
"peerDependencies": {
|
|
76
82
|
"react": "^18.0.0 || ^19.0.0",
|
|
@@ -97,5 +103,5 @@
|
|
|
97
103
|
"public"
|
|
98
104
|
]
|
|
99
105
|
},
|
|
100
|
-
"gitHead": "
|
|
106
|
+
"gitHead": "f846e7e21001a0fcbc4cd9f28c14a55cea7f4974"
|
|
101
107
|
}
|
|
@@ -7,10 +7,15 @@
|
|
|
7
7
|
* - Please do NOT modify this file.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
-
const PACKAGE_VERSION = '
|
|
11
|
-
const INTEGRITY_CHECKSUM = '
|
|
10
|
+
const PACKAGE_VERSION = '3.0.3'
|
|
11
|
+
const INTEGRITY_CHECKSUM = '5cd5cf8b54c3a90f82960cedcd637772'
|
|
12
12
|
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
|
|
13
|
+
|
|
13
14
|
const activeClientIds = new Set()
|
|
15
|
+
/**
|
|
16
|
+
* @type {Map<string, Set<Promise<Response>>>}
|
|
17
|
+
*/
|
|
18
|
+
const pendingRequests = new Map()
|
|
14
19
|
|
|
15
20
|
addEventListener('install', function () {
|
|
16
21
|
self.skipWaiting()
|
|
@@ -20,82 +25,101 @@ addEventListener('activate', function (event) {
|
|
|
20
25
|
event.waitUntil(self.clients.claim())
|
|
21
26
|
})
|
|
22
27
|
|
|
23
|
-
addEventListener('message',
|
|
28
|
+
addEventListener('message', function (event) {
|
|
24
29
|
const clientId = Reflect.get(event.source || {}, 'id')
|
|
25
30
|
|
|
26
31
|
if (!clientId || !self.clients) {
|
|
27
32
|
return
|
|
28
33
|
}
|
|
29
34
|
|
|
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
|
-
id: client.id,
|
|
67
|
-
frameType: client.frameType,
|
|
68
|
-
},
|
|
69
|
-
},
|
|
70
|
-
})
|
|
71
|
-
break
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
case 'CLIENT_CLOSED': {
|
|
75
|
-
activeClientIds.delete(clientId)
|
|
35
|
+
event.waitUntil(
|
|
36
|
+
(async () => {
|
|
37
|
+
if (event.data === 'CLIENT_CLOSE') {
|
|
38
|
+
const allClients = await self.clients.matchAll({
|
|
39
|
+
type: 'window',
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
activeClientIds.delete(clientId)
|
|
43
|
+
|
|
44
|
+
// Await any pending requests from the closing client.
|
|
45
|
+
// This makes sure that those requests are handled and not passthrough.
|
|
46
|
+
const pending = pendingRequests.get(clientId)
|
|
47
|
+
if (pending != null && pending.size > 0) {
|
|
48
|
+
await Promise.allSettled(pending)
|
|
49
|
+
}
|
|
50
|
+
pendingRequests.delete(clientId)
|
|
51
|
+
|
|
52
|
+
const remainingClients = allClients.filter((client) => {
|
|
53
|
+
return client.id !== clientId
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
// Unregister itself when there are no more clients
|
|
57
|
+
if (remainingClients.length === 0) {
|
|
58
|
+
await self.registration.unregister()
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const client = await self.clients.get(clientId)
|
|
62
|
+
|
|
63
|
+
if (client != null) {
|
|
64
|
+
await sendToClient(client, {
|
|
65
|
+
type: 'CLIENT_CLOSED',
|
|
66
|
+
})
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
return
|
|
70
|
+
}
|
|
76
71
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
72
|
+
/**
|
|
73
|
+
* @note Check for the client AFTER handling "CLIENT_CLOSE".
|
|
74
|
+
* This prevents early return on "!client" in case the page has reloaded
|
|
75
|
+
* and disassociated itself from the worker. This ensures self-unregistration
|
|
76
|
+
* still fires for those pages.
|
|
77
|
+
*/
|
|
78
|
+
const client = await self.clients.get(clientId)
|
|
80
79
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
self.registration.unregister()
|
|
80
|
+
if (!client) {
|
|
81
|
+
return
|
|
84
82
|
}
|
|
85
83
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
84
|
+
switch (event.data) {
|
|
85
|
+
case 'KEEPALIVE_REQUEST': {
|
|
86
|
+
await sendToClient(client, {
|
|
87
|
+
type: 'KEEPALIVE_RESPONSE',
|
|
88
|
+
})
|
|
89
|
+
break
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
case 'INTEGRITY_CHECK_REQUEST': {
|
|
93
|
+
await sendToClient(client, {
|
|
94
|
+
type: 'INTEGRITY_CHECK_RESPONSE',
|
|
95
|
+
payload: {
|
|
96
|
+
packageVersion: PACKAGE_VERSION,
|
|
97
|
+
checksum: INTEGRITY_CHECKSUM,
|
|
98
|
+
},
|
|
99
|
+
})
|
|
100
|
+
break
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
case 'MOCK_ACTIVATE': {
|
|
104
|
+
activeClientIds.add(clientId)
|
|
105
|
+
|
|
106
|
+
await sendToClient(client, {
|
|
107
|
+
type: 'MOCKING_ENABLED',
|
|
108
|
+
payload: {
|
|
109
|
+
client: {
|
|
110
|
+
id: client.id,
|
|
111
|
+
frameType: client.frameType,
|
|
112
|
+
},
|
|
113
|
+
},
|
|
114
|
+
})
|
|
115
|
+
break
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
})(),
|
|
119
|
+
)
|
|
89
120
|
})
|
|
90
121
|
|
|
91
122
|
addEventListener('fetch', function (event) {
|
|
92
|
-
const requestInterceptedAt = Date.now()
|
|
93
|
-
|
|
94
|
-
// Bypass navigation requests.
|
|
95
|
-
if (event.request.mode === 'navigate') {
|
|
96
|
-
return
|
|
97
|
-
}
|
|
98
|
-
|
|
99
123
|
// Opening the DevTools triggers the "only-if-cached" request
|
|
100
124
|
// that cannot be handled by the worker. Bypass such requests.
|
|
101
125
|
if (
|
|
@@ -113,23 +137,54 @@ addEventListener('fetch', function (event) {
|
|
|
113
137
|
}
|
|
114
138
|
|
|
115
139
|
const requestId = crypto.randomUUID()
|
|
116
|
-
event.respondWith(handleRequest(event, requestId
|
|
140
|
+
event.respondWith(handleRequest(event, requestId))
|
|
117
141
|
})
|
|
118
142
|
|
|
119
143
|
/**
|
|
120
144
|
* @param {FetchEvent} event
|
|
121
145
|
* @param {string} requestId
|
|
122
|
-
* @param {number} requestInterceptedAt
|
|
123
146
|
*/
|
|
124
|
-
async function handleRequest(event, requestId
|
|
147
|
+
async function handleRequest(event, requestId) {
|
|
125
148
|
const client = await resolveMainClient(event)
|
|
126
149
|
const requestCloneForEvents = event.request.clone()
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
150
|
+
|
|
151
|
+
const responsePromise = getResponse(event, client, requestId)
|
|
152
|
+
|
|
153
|
+
if (client != null) {
|
|
154
|
+
let pending = pendingRequests.get(client.id)
|
|
155
|
+
|
|
156
|
+
if (pending == null) {
|
|
157
|
+
pendingRequests.set(client.id, (pending = new Set()))
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
pending.add(responsePromise)
|
|
161
|
+
responsePromise
|
|
162
|
+
.finally(() => pending.delete(responsePromise))
|
|
163
|
+
.catch(() => {})
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
let response
|
|
167
|
+
|
|
168
|
+
try {
|
|
169
|
+
response = await responsePromise
|
|
170
|
+
} catch (error) {
|
|
171
|
+
// The request has settled without a response (e.g. a passthrough
|
|
172
|
+
// request failed with a network error). Notify the client so it
|
|
173
|
+
// can release the resources associated with this request.
|
|
174
|
+
if (client && activeClientIds.has(client.id)) {
|
|
175
|
+
sendToClient(client, {
|
|
176
|
+
type: 'REQUEST_ERROR',
|
|
177
|
+
payload: {
|
|
178
|
+
request: {
|
|
179
|
+
id: requestId,
|
|
180
|
+
},
|
|
181
|
+
error: serializeError(error),
|
|
182
|
+
},
|
|
183
|
+
})
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
throw error
|
|
187
|
+
}
|
|
133
188
|
|
|
134
189
|
// Send back the response clone for the "response:*" life-cycle events.
|
|
135
190
|
// Ensure MSW is active and ready to handle the message, otherwise
|
|
@@ -137,8 +192,18 @@ async function handleRequest(event, requestId, requestInterceptedAt) {
|
|
|
137
192
|
if (client && activeClientIds.has(client.id)) {
|
|
138
193
|
const serializedRequest = await serializeRequest(requestCloneForEvents)
|
|
139
194
|
|
|
195
|
+
// Omit the body of server-sent event stream responses.
|
|
196
|
+
// Cloning such responses would prevent client-side stream cancelations
|
|
197
|
+
// from reaching the original stream (a teed stream only cancels its
|
|
198
|
+
// source once both of its branches cancel) and would buffer the
|
|
199
|
+
// entire stream into the unconsumed clone indefinitely.
|
|
200
|
+
const isEventStreamResponse = response.headers
|
|
201
|
+
.get('content-type')
|
|
202
|
+
?.toLowerCase()
|
|
203
|
+
.startsWith('text/event-stream')
|
|
204
|
+
|
|
140
205
|
// Clone the response so both the client and the library could consume it.
|
|
141
|
-
const responseClone = response.clone()
|
|
206
|
+
const responseClone = isEventStreamResponse ? null : response.clone()
|
|
142
207
|
|
|
143
208
|
sendToClient(
|
|
144
209
|
client,
|
|
@@ -151,15 +216,17 @@ async function handleRequest(event, requestId, requestInterceptedAt) {
|
|
|
151
216
|
...serializedRequest,
|
|
152
217
|
},
|
|
153
218
|
response: {
|
|
154
|
-
type:
|
|
155
|
-
status:
|
|
156
|
-
statusText:
|
|
157
|
-
headers: Object.fromEntries(
|
|
158
|
-
body: responseClone.body,
|
|
219
|
+
type: response.type,
|
|
220
|
+
status: response.status,
|
|
221
|
+
statusText: response.statusText,
|
|
222
|
+
headers: Object.fromEntries(response.headers.entries()),
|
|
223
|
+
body: responseClone ? responseClone.body : null,
|
|
159
224
|
},
|
|
160
225
|
},
|
|
161
226
|
},
|
|
162
|
-
responseClone
|
|
227
|
+
responseClone && responseClone.body
|
|
228
|
+
? [serializedRequest.body, responseClone.body]
|
|
229
|
+
: [],
|
|
163
230
|
)
|
|
164
231
|
}
|
|
165
232
|
|
|
@@ -205,18 +272,32 @@ async function resolveMainClient(event) {
|
|
|
205
272
|
* @param {FetchEvent} event
|
|
206
273
|
* @param {Client | undefined} client
|
|
207
274
|
* @param {string} requestId
|
|
208
|
-
* @param {number} requestInterceptedAt
|
|
209
275
|
* @returns {Promise<Response>}
|
|
210
276
|
*/
|
|
211
|
-
async function getResponse(event, client, requestId
|
|
277
|
+
async function getResponse(event, client, requestId) {
|
|
212
278
|
// Clone the request because it might've been already used
|
|
213
279
|
// (i.e. its body has been read and sent to the client).
|
|
214
280
|
const requestClone = event.request.clone()
|
|
215
281
|
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
282
|
+
/**
|
|
283
|
+
* @param {{ request?: { headers?: Array<[string, string]> } }} [data]
|
|
284
|
+
*/
|
|
285
|
+
function passthrough(data) {
|
|
286
|
+
const headers = new Headers()
|
|
287
|
+
const requestHeaders = data?.request?.headers
|
|
288
|
+
|
|
289
|
+
if (Array.isArray(requestHeaders)) {
|
|
290
|
+
// Apply the request headers provided by the client.
|
|
291
|
+
// Those reflect any modifications made in the request handlers.
|
|
292
|
+
// Use ".append()" to support multiple headers with the same name.
|
|
293
|
+
for (const [name, value] of requestHeaders) {
|
|
294
|
+
headers.append(name, value)
|
|
295
|
+
}
|
|
296
|
+
} else {
|
|
297
|
+
for (const [name, value] of requestClone.headers) {
|
|
298
|
+
headers.append(name, value)
|
|
299
|
+
}
|
|
300
|
+
}
|
|
220
301
|
|
|
221
302
|
// Remove the "accept" header value that marked this request as passthrough.
|
|
222
303
|
// This prevents request alteration and also keeps it compliant with the
|
|
@@ -259,7 +340,6 @@ async function getResponse(event, client, requestId, requestInterceptedAt) {
|
|
|
259
340
|
type: 'REQUEST',
|
|
260
341
|
payload: {
|
|
261
342
|
id: requestId,
|
|
262
|
-
interceptedAt: requestInterceptedAt,
|
|
263
343
|
...serializedRequest,
|
|
264
344
|
},
|
|
265
345
|
},
|
|
@@ -268,17 +348,35 @@ async function getResponse(event, client, requestId, requestInterceptedAt) {
|
|
|
268
348
|
|
|
269
349
|
switch (clientMessage.type) {
|
|
270
350
|
case 'MOCK_RESPONSE': {
|
|
271
|
-
return respondWithMock(clientMessage.data)
|
|
351
|
+
return respondWithMock(clientMessage.data, event)
|
|
272
352
|
}
|
|
273
353
|
|
|
274
354
|
case 'PASSTHROUGH': {
|
|
275
|
-
return passthrough()
|
|
355
|
+
return passthrough(clientMessage.data)
|
|
276
356
|
}
|
|
277
357
|
}
|
|
278
358
|
|
|
279
359
|
return passthrough()
|
|
280
360
|
}
|
|
281
361
|
|
|
362
|
+
/**
|
|
363
|
+
* @param {unknown} error
|
|
364
|
+
* @returns {{ name: string, message: string }}
|
|
365
|
+
*/
|
|
366
|
+
function serializeError(error) {
|
|
367
|
+
if (error instanceof Error) {
|
|
368
|
+
return {
|
|
369
|
+
name: error.name,
|
|
370
|
+
message: error.message,
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
return {
|
|
375
|
+
name: 'Error',
|
|
376
|
+
message: String(error),
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
282
380
|
/**
|
|
283
381
|
* @param {Client} client
|
|
284
382
|
* @param {any} message
|
|
@@ -306,9 +404,10 @@ function sendToClient(client, message, transferrables = []) {
|
|
|
306
404
|
|
|
307
405
|
/**
|
|
308
406
|
* @param {Response} response
|
|
309
|
-
* @
|
|
407
|
+
* @param {FetchEvent} event
|
|
408
|
+
* @returns {Promise<Response>}
|
|
310
409
|
*/
|
|
311
|
-
function respondWithMock(response) {
|
|
410
|
+
async function respondWithMock(response, event) {
|
|
312
411
|
// Setting response status code to 0 is a no-op.
|
|
313
412
|
// However, when responding with a "Response.error()", the produced Response
|
|
314
413
|
// instance will have status code set to 0. Since it's not possible to create
|
|
@@ -317,7 +416,19 @@ function respondWithMock(response) {
|
|
|
317
416
|
return Response.error()
|
|
318
417
|
}
|
|
319
418
|
|
|
320
|
-
|
|
419
|
+
let body = response.body
|
|
420
|
+
|
|
421
|
+
// Buffer the streamed mocked response body for navigation requests.
|
|
422
|
+
// The stream is transferred from the client that is being navigated
|
|
423
|
+
// away from. Once the navigation commits, that client gets destroyed
|
|
424
|
+
// and the stream will never complete, resulting in an empty document.
|
|
425
|
+
// Buffering here keeps "event.respondWith()" pending (the navigation
|
|
426
|
+
// cannot commit) until the entire body arrives from the client.
|
|
427
|
+
if (event.request.mode === 'navigate' && body instanceof ReadableStream) {
|
|
428
|
+
body = await new Response(body).arrayBuffer()
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
const mockedResponse = new Response(body, response)
|
|
321
432
|
|
|
322
433
|
Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
|
|
323
434
|
value: true,
|
package/dist/esm/withMSW.js
DELETED
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
import { setupWorker } from "msw/browser";
|
|
2
|
-
import { useEffect, useGlobals, useParameter, useRef, } from "storybook/internal/preview-api";
|
|
3
|
-
import { KEY, PARAM_KEY } from "./constants.js";
|
|
4
|
-
// Singleton worker instance
|
|
5
|
-
let worker = null;
|
|
6
|
-
let workerPromise = null;
|
|
7
|
-
const initializeWorker = async () => {
|
|
8
|
-
if (workerPromise) {
|
|
9
|
-
return workerPromise;
|
|
10
|
-
}
|
|
11
|
-
workerPromise = (async () => {
|
|
12
|
-
try {
|
|
13
|
-
worker = setupWorker();
|
|
14
|
-
await worker.start({
|
|
15
|
-
serviceWorker: { url: "/mockServiceWorker.js" },
|
|
16
|
-
onUnhandledRequest: "bypass",
|
|
17
|
-
});
|
|
18
|
-
return worker;
|
|
19
|
-
}
|
|
20
|
-
catch (error) {
|
|
21
|
-
console.warn("[MSW Addon] Failed to initialize worker:", error);
|
|
22
|
-
worker = null;
|
|
23
|
-
workerPromise = null;
|
|
24
|
-
return null;
|
|
25
|
-
}
|
|
26
|
-
})();
|
|
27
|
-
return workerPromise;
|
|
28
|
-
};
|
|
29
|
-
/**
|
|
30
|
-
* Whether MSW should serve this story. The toolbar stores the global as a
|
|
31
|
-
* boolean, and only an explicit `false` turns it off; a story opts out with
|
|
32
|
-
* `parameters.msw.disable`.
|
|
33
|
-
*/
|
|
34
|
-
const isActive = (globalValue, parameter) => globalValue !== false && !(parameter?.disable ?? false);
|
|
35
|
-
/**
|
|
36
|
-
* Install the story's handlers on a started worker, or clear them when MSW is
|
|
37
|
-
* off for the story. A worker that failed to start leaves the story to run
|
|
38
|
-
* against the network.
|
|
39
|
-
*/
|
|
40
|
-
const applyHandlers = async (active, handlers) => {
|
|
41
|
-
if (!active) {
|
|
42
|
-
worker?.resetHandlers();
|
|
43
|
-
return;
|
|
44
|
-
}
|
|
45
|
-
const activeWorker = await initializeWorker();
|
|
46
|
-
if (!activeWorker)
|
|
47
|
-
return;
|
|
48
|
-
activeWorker.resetHandlers();
|
|
49
|
-
if (handlers && handlers.length > 0) {
|
|
50
|
-
activeWorker.use(...handlers);
|
|
51
|
-
}
|
|
52
|
-
};
|
|
53
|
-
/**
|
|
54
|
-
* Starts the worker and installs the story's handlers before the story
|
|
55
|
-
* renders. Storybook awaits loaders before it renders a story and before its
|
|
56
|
-
* play function runs, so the story's first render already has its mocks and a
|
|
57
|
-
* play function never waits on MSW.
|
|
58
|
-
*/
|
|
59
|
-
export const mswLoader = async ({ globals, parameters, }) => {
|
|
60
|
-
const parameter = parameters[PARAM_KEY];
|
|
61
|
-
await applyHandlers(isActive(globals[KEY], parameter), parameter?.handlers);
|
|
62
|
-
return {};
|
|
63
|
-
};
|
|
64
|
-
/**
|
|
65
|
-
* Keeps the handlers in step with the toolbar toggle while a story is shown.
|
|
66
|
-
* It never holds the story back: the loader has already started the worker,
|
|
67
|
-
* and preview-hook effects only run once the story and its play function have
|
|
68
|
-
* finished, so gating the render here would deadlock a play function.
|
|
69
|
-
*/
|
|
70
|
-
export const withMSW = (StoryFn) => {
|
|
71
|
-
const [globals] = useGlobals();
|
|
72
|
-
const parameter = useParameter(PARAM_KEY);
|
|
73
|
-
const active = isActive(globals[KEY], parameter);
|
|
74
|
-
// The handlers array is a new reference on every render even when its
|
|
75
|
-
// contents are the same; read it through a ref so the effect does not re-run.
|
|
76
|
-
const handlersRef = useRef(parameter?.handlers);
|
|
77
|
-
handlersRef.current = parameter?.handlers;
|
|
78
|
-
useEffect(() => {
|
|
79
|
-
void applyHandlers(active, handlersRef.current);
|
|
80
|
-
return () => {
|
|
81
|
-
worker?.resetHandlers();
|
|
82
|
-
};
|
|
83
|
-
}, [active]);
|
|
84
|
-
return StoryFn();
|
|
85
|
-
};
|
|
86
|
-
//# sourceMappingURL=withMSW.js.map
|
package/dist/esm/withMSW.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"withMSW.js","sourceRoot":"","sources":["../../src/withMSW.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoB,WAAW,EAAE,MAAM,aAAa,CAAC;AAC5D,OAAO,EACL,SAAS,EACT,UAAU,EACV,YAAY,EACZ,MAAM,GACP,MAAM,gCAAgC,CAAC;AAMxC,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAGhD,4BAA4B;AAC5B,IAAI,MAAM,GAAuB,IAAI,CAAC;AACtC,IAAI,aAAa,GAAuC,IAAI,CAAC;AAE7D,MAAM,gBAAgB,GAAG,KAAK,IAAiC,EAAE;IAC/D,IAAI,aAAa,EAAE,CAAC;QAClB,OAAO,aAAa,CAAC;IACvB,CAAC;IAED,aAAa,GAAG,CAAC,KAAK,IAAI,EAAE;QAC1B,IAAI,CAAC;YACH,MAAM,GAAG,WAAW,EAAE,CAAC;YACvB,MAAM,MAAM,CAAC,KAAK,CAAC;gBACjB,aAAa,EAAE,EAAE,GAAG,EAAE,uBAAuB,EAAE;gBAC/C,kBAAkB,EAAE,QAAQ;aAC7B,CAAC,CAAC;YACH,OAAO,MAAM,CAAC;QAChB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,IAAI,C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C,OAAO,CAAC,GAAG,UAAU,EAAE,CAAC;IAC/B,MAAM,SAAS,GAAG,YAAY,CAAe,SAAS,CAAC,CAAC;IACxD,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,SAAS,CAAC,CAAC;IAEjD,sEAAsE;IACtE,8EAA8E;IAC9E,MAAM,WAAW,GAAG,MAAM,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;IAChD,WAAW,CAAC,OAAO,GAAG,SAAS,EAAE,QAAQ,CAAC;IAE1C,SAAS,CAAC,GAAG,EAAE;QACb,KAAK,aAAa,CAAC,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC;QAChD,OAAO,GAAG,EAAE;YACV,MAAM,EAAE,aAAa,EAAE,CAAC;QAC1B,CAAC,CAAC;IACJ,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;IAEb,OAAO,OAAO,EAAE,CAAC;AACnB,CAAC,CAAC"}
|
package/dist/types/withMSW.d.ts
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import type { LoaderFunction, Renderer, PartialStoryFn as StoryFunction } from "storybook/internal/types";
|
|
2
|
-
/**
|
|
3
|
-
* Starts the worker and installs the story's handlers before the story
|
|
4
|
-
* renders. Storybook awaits loaders before it renders a story and before its
|
|
5
|
-
* play function runs, so the story's first render already has its mocks and a
|
|
6
|
-
* play function never waits on MSW.
|
|
7
|
-
*/
|
|
8
|
-
export declare const mswLoader: LoaderFunction<Renderer>;
|
|
9
|
-
/**
|
|
10
|
-
* Keeps the handlers in step with the toolbar toggle while a story is shown.
|
|
11
|
-
* It never holds the story back: the loader has already started the worker,
|
|
12
|
-
* and preview-hook effects only run once the story and its play function have
|
|
13
|
-
* finished, so gating the render here would deadlock a play function.
|
|
14
|
-
*/
|
|
15
|
-
export declare const withMSW: (StoryFn: StoryFunction<Renderer>) => any;
|
|
16
|
-
//# sourceMappingURL=withMSW.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"withMSW.d.ts","sourceRoot":"","sources":["../../src/withMSW.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EACV,cAAc,EACd,QAAQ,EACR,cAAc,IAAI,aAAa,EAChC,MAAM,0BAA0B,CAAC;AA+DlC;;;;;GAKG;AACH,eAAO,MAAM,SAAS,EAAE,cAAc,CAAC,QAAQ,CAO9C,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,OAAO,YAAa,aAAa,CAAC,QAAQ,CAAC,QAkBvD,CAAC"}
|