/
instrumenter.ts
607 lines (534 loc) · 21.9 KB
/
instrumenter.ts
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
/* eslint-disable no-underscore-dangle */
import { addons, Channel } from '@storybook/addons';
import type { StoryId } from '@storybook/addons';
import { logger, once } from '@storybook/client-logger';
import {
FORCE_REMOUNT,
IGNORED_EXCEPTION,
SET_CURRENT_STORY,
STORY_RENDER_PHASE_CHANGED,
} from '@storybook/core-events';
import global from 'global';
import { Call, CallRef, CallStates, ControlStates, LogItem, Options, State } from './types';
export const EVENTS = {
CALL: 'instrumenter/call',
SYNC: 'instrumenter/sync',
START: 'instrumenter/start',
BACK: 'instrumenter/back',
GOTO: 'instrumenter/goto',
NEXT: 'instrumenter/next',
END: 'instrumenter/end',
};
type PatchedObj<TObj> = {
[Property in keyof TObj]: TObj[Property] & { __originalFn__: PatchedObj<TObj> };
};
const debuggerDisabled = global.FEATURES?.interactionsDebugger !== true;
const controlsDisabled: ControlStates = {
debugger: !debuggerDisabled,
start: false,
back: false,
goto: false,
next: false,
end: false,
};
const alreadyCompletedException = new Error(
`This function ran after the play function completed. Did you forget to \`await\` it?`
);
const isObject = (o: unknown) => Object.prototype.toString.call(o) === '[object Object]';
const isModule = (o: unknown) => Object.prototype.toString.call(o) === '[object Module]';
const isInstrumentable = (o: unknown) => {
if (!isObject(o) && !isModule(o)) return false;
if (o.constructor === undefined) return true;
const proto = o.constructor.prototype;
if (!isObject(proto)) return false;
if (Object.prototype.hasOwnProperty.call(proto, 'isPrototypeOf') === false) return false;
return true;
};
const construct = (obj: any) => {
try {
return new obj.constructor();
} catch (e) {
return {};
}
};
const getInitialState = (): State => ({
renderPhase: undefined,
isDebugging: false,
isPlaying: false,
isLocked: false,
cursor: 0,
calls: [],
shadowCalls: [],
callRefsByResult: new Map(),
chainedCallIds: new Set<Call['id']>(),
parentId: undefined,
playUntil: undefined,
resolvers: {},
syncTimeout: undefined,
});
const getRetainedState = (state: State, isDebugging = false) => {
const calls = (isDebugging ? state.shadowCalls : state.calls).filter((call) => call.retain);
if (!calls.length) return undefined;
const callRefsByResult = new Map(
Array.from(state.callRefsByResult.entries()).filter(([, ref]) => ref.retain)
);
return { cursor: calls.length, calls, callRefsByResult };
};
/**
* This class is not supposed to be used directly. Use the `instrument` function below instead.
*/
export class Instrumenter {
channel: Channel;
initialized = false;
// State is tracked per story to deal with multiple stories on the same canvas (i.e. docs mode)
state: Record<StoryId, State>;
constructor() {
this.channel = addons.getChannel();
// Restore state from the parent window in case the iframe was reloaded.
this.state = global.window.parent.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER_STATE__ || {};
// When called from `start`, isDebugging will be true
const resetState = ({
storyId,
isPlaying = true,
isDebugging = false,
}: {
storyId?: StoryId;
isPlaying?: boolean;
isDebugging?: boolean;
}) => {
const state = this.getState(storyId);
this.setState(storyId, {
...getInitialState(),
...getRetainedState(state, isDebugging),
shadowCalls: isDebugging ? state.shadowCalls : [],
chainedCallIds: isDebugging ? state.chainedCallIds : new Set<Call['id']>(),
playUntil: isDebugging ? state.playUntil : undefined,
isPlaying,
isDebugging,
});
// Don't sync while debugging, as it'll cause flicker.
if (!isDebugging) this.sync(storyId);
};
// A forceRemount might be triggered for debugging (on `start`), or elsewhere in Storybook.
this.channel.on(FORCE_REMOUNT, resetState);
// Start with a clean slate before playing after a remount, and stop debugging when done.
this.channel.on(STORY_RENDER_PHASE_CHANGED, ({ storyId, newPhase }) => {
const { isDebugging } = this.getState(storyId);
this.setState(storyId, { renderPhase: newPhase });
if (newPhase === 'preparing' && isDebugging) {
resetState({ storyId });
}
if (newPhase === 'playing') {
resetState({ storyId, isDebugging });
}
if (newPhase === 'played') {
this.setState(storyId, {
isLocked: false,
isPlaying: false,
isDebugging: false,
});
}
if (newPhase === 'errored') {
this.setState(storyId, {
isLocked: false,
isPlaying: false,
});
}
});
// Trash non-retained state and clear the log when switching stories, but not on initial boot.
this.channel.on(SET_CURRENT_STORY, () => {
if (this.initialized) this.cleanup();
else this.initialized = true;
});
const start = ({ storyId, playUntil }: { storyId: string; playUntil?: Call['id'] }) => {
if (!this.getState(storyId).isDebugging) {
this.setState(storyId, ({ calls }) => ({
calls: [],
shadowCalls: calls.map((call) => ({ ...call, status: CallStates.WAITING })),
isDebugging: true,
}));
}
const log = this.getLog(storyId);
this.setState(storyId, ({ shadowCalls }) => {
const firstRowIndex = shadowCalls.findIndex((call) => call.id === log[0].callId);
return {
playUntil:
playUntil ||
shadowCalls
.slice(0, firstRowIndex)
.filter((call) => call.interceptable && !call.parentId)
.slice(-1)[0]?.id,
};
});
// Force remount may trigger a page reload if the play function can't be aborted.
this.channel.emit(FORCE_REMOUNT, { storyId, isDebugging: true });
};
const back = ({ storyId }: { storyId: string }) => {
const log = this.getLog(storyId).filter((call) => !call.parentId);
const last = log.reduceRight((res, item, index) => {
if (res >= 0 || item.status === CallStates.WAITING) return res;
return index;
}, -1);
start({ storyId, playUntil: log[last - 1]?.callId });
};
const goto = ({ storyId, callId }: { storyId: string; callId: Call['id'] }) => {
const { calls, shadowCalls, resolvers } = this.getState(storyId);
const call = calls.find(({ id }) => id === callId);
const shadowCall = shadowCalls.find(({ id }) => id === callId);
if (!call && shadowCall && Object.values(resolvers).length > 0) {
const nextId = this.getLog(storyId).find((c) => c.status === CallStates.WAITING)?.callId;
if (shadowCall.id !== nextId) this.setState(storyId, { playUntil: shadowCall.id });
Object.values(resolvers).forEach((resolve) => resolve());
} else {
start({ storyId, playUntil: callId });
}
};
const next = ({ storyId }: { storyId: string }) => {
const { resolvers } = this.getState(storyId);
if (Object.values(resolvers).length > 0) {
Object.values(resolvers).forEach((resolve) => resolve());
} else {
const nextId = this.getLog(storyId).find((c) => c.status === CallStates.WAITING)?.callId;
if (nextId) start({ storyId, playUntil: nextId });
else end({ storyId });
}
};
const end = ({ storyId }: { storyId: string }) => {
this.setState(storyId, { playUntil: undefined, isDebugging: false });
Object.values(this.getState(storyId).resolvers).forEach((resolve) => resolve());
};
this.channel.on(EVENTS.START, start);
this.channel.on(EVENTS.BACK, back);
this.channel.on(EVENTS.GOTO, goto);
this.channel.on(EVENTS.NEXT, next);
this.channel.on(EVENTS.END, end);
}
getState(storyId: StoryId) {
return this.state[storyId] || getInitialState();
}
setState(storyId: StoryId, update: Partial<State> | ((state: State) => Partial<State>)) {
const state = this.getState(storyId);
const patch = typeof update === 'function' ? update(state) : update;
this.state = { ...this.state, [storyId]: { ...state, ...patch } };
// Track state on the parent window so we can reload the iframe without losing state.
global.window.parent.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER_STATE__ = this.state;
}
cleanup() {
// Reset stories with retained state to their initial state, and drop the rest.
this.state = Object.entries(this.state).reduce((acc, [storyId, state]) => {
const retainedState = getRetainedState(state);
if (!retainedState) return acc;
acc[storyId] = Object.assign(getInitialState(), retainedState);
return acc;
}, {} as Record<StoryId, State>);
this.channel.emit(EVENTS.SYNC, { controlStates: controlsDisabled, logItems: [] });
global.window.parent.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER_STATE__ = this.state;
}
getLog(storyId: string): LogItem[] {
const { calls, shadowCalls } = this.getState(storyId);
const merged = [...shadowCalls];
calls.forEach((call, index) => {
merged[index] = call;
});
const seen = new Set();
return merged.reduceRight<LogItem[]>((acc, call) => {
call.args.forEach((arg) => {
if (arg?.__callId__) {
seen.add(arg.__callId__);
}
});
call.path.forEach((node) => {
if ((node as CallRef).__callId__) {
seen.add((node as CallRef).__callId__);
}
});
if ((call.interceptable || call.exception) && !seen.has(call.id)) {
acc.unshift({ callId: call.id, status: call.status, parentId: call.parentId });
seen.add(call.id);
}
return acc;
}, []);
}
// Traverses the object structure to recursively patch all function properties.
// Returns the original object, or a new object with the same constructor,
// depending on whether it should mutate.
instrument<TObj extends { [x: string]: any }>(obj: TObj, options: Options): PatchedObj<TObj> {
if (!isInstrumentable(obj)) return obj;
const { mutate = false, path = [] } = options;
return Object.keys(obj).reduce(
(acc, key) => {
const value = (obj as Record<string, any>)[key];
// Nothing to patch, but might be instrumentable, so we recurse
if (typeof value !== 'function') {
acc[key] = this.instrument(value, { ...options, path: path.concat(key) });
return acc;
}
// Already patched, so we pass through unchanged
if (typeof value.__originalFn__ === 'function') {
acc[key] = value;
return acc;
}
// Patch the function and mark it "patched" by adding a reference to the original function
acc[key] = (...args: any[]) => this.track(key, value, args, options);
acc[key].__originalFn__ = value;
// Reuse the original name as the patched function's name
Object.defineProperty(acc[key], 'name', { value: key, writable: false });
// Deal with functions that also act like an object
if (Object.keys(value).length > 0) {
Object.assign(
acc[key],
this.instrument({ ...value }, { ...options, path: path.concat(key) })
);
}
return acc;
},
mutate ? obj : construct(obj)
);
}
// Monkey patch an object method to record calls.
// Returns a function that invokes the original function, records the invocation ("call") and
// returns the original result.
track(method: string, fn: Function, args: any[], options: Options) {
const storyId: StoryId =
args?.[0]?.__storyId__ || global.window.__STORYBOOK_PREVIEW__?.urlStore?.selection?.storyId;
const { cursor, parentId } = this.getState(storyId);
this.setState(storyId, { cursor: cursor + 1 });
const id = `${parentId || storyId} [${cursor}] ${method}`;
const { path = [], intercept = false, retain = false } = options;
const interceptable = typeof intercept === 'function' ? intercept(method, path) : intercept;
const call: Call = { id, parentId, storyId, cursor, path, method, args, interceptable, retain };
const interceptOrInvoke = interceptable && !parentId ? this.intercept : this.invoke;
const result = interceptOrInvoke.call(this, fn, call, options);
return this.instrument(result, { ...options, mutate: true, path: [{ __callId__: call.id }] });
}
intercept(fn: Function, call: Call, options: Options) {
const { chainedCallIds, isDebugging, playUntil } = this.getState(call.storyId);
// For a "jump to step" action, continue playing until we hit a call by that ID.
// For chained calls, we can only return a Promise for the last call in the chain.
const isChainedUpon = chainedCallIds.has(call.id);
if (!isDebugging || isChainedUpon || playUntil) {
if (playUntil === call.id) {
this.setState(call.storyId, { playUntil: undefined });
}
return this.invoke(fn, call, options);
}
// Instead of invoking the function, defer the function call until we continue playing.
return new Promise((resolve) => {
this.setState(call.storyId, ({ resolvers }) => ({
isLocked: false,
resolvers: { ...resolvers, [call.id]: resolve },
}));
}).then(() => {
this.setState(call.storyId, (state) => {
const { [call.id]: _, ...resolvers } = state.resolvers;
return { isLocked: true, resolvers };
});
return this.invoke(fn, call, options);
});
}
invoke(fn: Function, call: Call, options: Options) {
// TODO this doesnt work because the abortSignal we have here is the newly created one
// const { abortSignal } = global.window.__STORYBOOK_PREVIEW__ || {};
// if (abortSignal && abortSignal.aborted) throw IGNORED_EXCEPTION;
const { callRefsByResult, renderPhase } = this.getState(call.storyId);
// Map complex values to a JSON-serializable representation.
const serializeValues = (value: any): any => {
if (callRefsByResult.has(value)) {
return callRefsByResult.get(value);
}
if (value instanceof Array) {
return value.map(serializeValues);
}
if (value instanceof Date) {
return { __date__: { value: value.toISOString() } };
}
if (value instanceof Error) {
const { name, message, stack } = value;
return { __error__: { name, message, stack } };
}
if (value instanceof RegExp) {
const { flags, source } = value;
return { __regexp__: { flags, source } };
}
if (value instanceof global.window.HTMLElement) {
const { prefix, localName, id, classList, innerText } = value;
const classNames = Array.from(classList);
return { __element__: { prefix, localName, id, classNames, innerText } };
}
if (typeof value === 'function') {
return { __function__: { name: value.name } };
}
if (typeof value === 'symbol') {
return { __symbol__: { description: value.description } };
}
if (
typeof value === 'object' &&
value?.constructor?.name &&
value?.constructor?.name !== 'Object'
) {
return { __class__: { name: value.constructor.name } };
}
return value;
};
const info: Call = { ...call, args: call.args.map(serializeValues) };
// Mark any ancestor calls as "chained upon" so we won't attempt to defer it later.
call.path.forEach((ref: any) => {
if (ref?.__callId__) {
this.setState(call.storyId, ({ chainedCallIds }) => ({
chainedCallIds: new Set(Array.from(chainedCallIds).concat(ref.__callId__)),
}));
}
});
const handleException = (e: any) => {
if (e instanceof Error) {
const { name, message, stack, callId = call.id } = e as Error & { callId: Call['id'] };
const exception = { name, message, stack, callId };
this.update({ ...info, status: CallStates.ERROR, exception });
// Always track errors to their originating call.
this.setState(call.storyId, (state) => ({
callRefsByResult: new Map([
...Array.from(state.callRefsByResult.entries()),
[e, { __callId__: call.id, retain: call.retain }],
]),
}));
// Exceptions inside callbacks should bubble up to the parent call.
if (call.parentId) {
Object.defineProperty(e, 'callId', { value: call.id });
throw e;
}
// We need to throw to break out of the play function, but we don't want to trigger a redbox
// so we throw an ignoredException, which is caught and silently ignored by Storybook.
if (e !== alreadyCompletedException) {
logger.warn(e);
throw IGNORED_EXCEPTION;
}
}
throw e;
};
try {
if (renderPhase === 'played' && !call.retain) {
throw alreadyCompletedException;
}
// Some libraries override function args through the `getArgs` option.
const actualArgs = options.getArgs
? options.getArgs(call, this.getState(call.storyId))
: call.args;
// Wrap any callback functions to provide a way to access their "parent" call.
// This is picked up in the `track` function and used for call metadata.
const finalArgs = actualArgs.map((arg: any) => {
// We only want to wrap plain functions, not objects.
if (typeof arg !== 'function' || Object.keys(arg).length) return arg;
return (...args: any) => {
// Set the cursor and parentId for calls that happen inside the callback.
const { cursor, parentId } = this.getState(call.storyId);
this.setState(call.storyId, { cursor: 0, parentId: call.id });
const restore = () => this.setState(call.storyId, { cursor, parentId });
// Invoke the actual callback function.
const res = arg(...args);
// Reset cursor and parentId to their original values before we entered the callback.
if (res instanceof Promise) res.then(restore, restore);
else restore();
return res;
};
});
const result = fn(...finalArgs);
// Track the result so we can trace later uses of it back to the originating call.
// Primitive results (undefined, null, boolean, string, number, BigInt) are ignored.
if (result && ['object', 'function', 'symbol'].includes(typeof result)) {
this.setState(call.storyId, (state) => ({
callRefsByResult: new Map([
...Array.from(state.callRefsByResult.entries()),
[result, { __callId__: call.id, retain: call.retain }],
]),
}));
}
this.update({
...info,
status: result instanceof Promise ? CallStates.ACTIVE : CallStates.DONE,
});
if (result instanceof Promise) {
return result.then((value) => {
this.update({ ...info, status: CallStates.DONE });
return value;
}, handleException);
}
return result;
} catch (e) {
return handleException(e);
}
}
// Sends the call info and log to the manager.
// Uses a 0ms debounce because this might get called many times in one tick.
update(call: Call) {
clearTimeout(this.getState(call.storyId).syncTimeout);
this.channel.emit(EVENTS.CALL, call);
this.setState(call.storyId, ({ calls }) => {
// Omit earlier calls for the same ID, which may have been superceded by a later invocation.
// This typically happens when calls are part of a callback which runs multiple times.
const callsById = calls
.concat(call)
.reduce<Record<Call['id'], Call>>((a, c) => Object.assign(a, { [c.id]: c }), {});
return {
// Calls are sorted to ensure parent calls always come before calls in their callback.
calls: Object.values(callsById).sort((a, b) =>
a.id.localeCompare(b.id, undefined, { numeric: true })
),
syncTimeout: setTimeout(() => this.sync(call.storyId), 0),
};
});
}
sync(storyId: StoryId) {
const { isLocked, isPlaying } = this.getState(storyId);
const logItems: LogItem[] = this.getLog(storyId);
const pausedAt = logItems
.filter(({ parentId }) => !parentId)
.find((item) => item.status === CallStates.WAITING)?.callId;
const hasActive = logItems.some((item) => item.status === CallStates.ACTIVE);
if (debuggerDisabled || isLocked || hasActive || logItems.length === 0) {
this.channel.emit(EVENTS.SYNC, { controlStates: controlsDisabled, logItems });
return;
}
const hasPrevious = logItems.some((item) =>
[CallStates.DONE, CallStates.ERROR].includes(item.status)
);
const controlStates: ControlStates = {
debugger: true,
start: hasPrevious,
back: hasPrevious,
goto: true,
next: isPlaying,
end: isPlaying,
};
this.channel.emit(EVENTS.SYNC, { controlStates, logItems, pausedAt });
}
}
/**
* Instruments an object or module by traversing its properties, patching any functions (methods)
* to enable debugging. Patched functions will emit a `call` event when invoked.
* When intercept = true, patched functions will return a Promise when the debugger stops before
* this function. As such, "interceptable" functions will have to be `await`-ed.
*/
export function instrument<TObj extends Record<string, any>>(
obj: TObj,
options: Options = {}
): TObj {
try {
// Don't do any instrumentation if not loaded in an iframe and it's not running in a capture.
if (global.window.parent === global.window) {
const params = new URLSearchParams(global.window.location.search);
if (!params.get('interactions')) {
return obj;
}
}
// Only create an instance if we don't have one (singleton) yet.
if (!global.window.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER__) {
global.window.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER__ = new Instrumenter();
}
const instrumenter: Instrumenter = global.window.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER__;
return instrumenter.instrument(obj, options);
} catch (e) {
// Access to the parent window might fail due to CORS restrictions.
once.warn(e);
return obj;
}
}