main
js 63 lines 1.48 KB
Raw
1 /**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * @flow
8 */
9
10 import type {Fiber} from './ReactInternalTypes';
11
12 import {getStackByFiberInDevAndProd} from './ReactFiberComponentStack';
13
14 const CapturedStacks: WeakMap<any, CapturedValue<any>> = new WeakMap();
15
16 export type CapturedValue<+T> = {
17 +value: T,
18 source: Fiber | null,
19 stack: string | null,
20 };
21
22 export function createCapturedValueAtFiber<T>(
23 value: T,
24 source: Fiber,
25 ): CapturedValue<T> {
26 // If the value is an error, call this function immediately after it is thrown
27 // so the stack is accurate.
28 // $FlowFixMe[invalid-compare]
29 if (typeof value === 'object' && value !== null) {
30 const existing = CapturedStacks.get(value);
31 if (existing !== undefined) {
32 return existing;
33 }
34 const captured: CapturedValue<T> = {
35 value,
36 source,
37 stack: getStackByFiberInDevAndProd(source),
38 };
39 CapturedStacks.set(value, captured);
40 return captured;
41 } else {
42 return {
43 value,
44 source,
45 stack: getStackByFiberInDevAndProd(source),
46 };
47 }
48 }
49
50 export function createCapturedValueFromError(
51 value: Error,
52 stack: null | string,
53 ): CapturedValue<Error> {
54 const captured: CapturedValue<Error> = {
55 value,
56 source: null,
57 stack: stack,
58 };
59 if (typeof stack === 'string') {
60 CapturedStacks.set(value, captured);
61 }
62 return captured;
63 }