| 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 { |
| 11 | Thenable, |
| 12 | FulfilledThenable, |
| 13 | RejectedThenable, |
| 14 | ReactDebugInfo, |
| 15 | ReactIOInfo, |
| 16 | ReactAsyncInfo, |
| 17 | } from 'shared/ReactTypes'; |
| 18 | |
| 19 | import type {ModuleLoading} from 'react-client/src/ReactFlightClientConfig'; |
| 20 | |
| 21 | export type ServerConsumerModuleMap = string; // Module root path |
| 22 | |
| 23 | export type ServerManifest = string; // Module root path |
| 24 | |
| 25 | export type ServerReferenceId = string; |
| 26 | |
| 27 | import {prepareDestinationForModuleImpl} from 'react-client/src/ReactFlightClientConfig'; |
| 28 | |
| 29 | export opaque type ClientReferenceMetadata = [ |
| 30 | string, // module path |
| 31 | string, // export name |
| 32 | ]; |
| 33 | |
| 34 | // eslint-disable-next-line no-unused-vars |
| 35 | export opaque type ClientReference<T> = { |
| 36 | specifier: string, |
| 37 | name: string, |
| 38 | }; |
| 39 | |
| 40 | // The reason this function needs to defined here in this file instead of just |
| 41 | // being exported directly from the WebpackDestination... file is because the |
| 42 | // ClientReferenceMetadata is opaque and we can't unwrap it there. |
| 43 | // This should get inlined and we could also just implement an unwrapping function |
| 44 | // though that risks it getting used in places it shouldn't be. This is unfortunate |
| 45 | // but currently it seems to be the best option we have. |
| 46 | export function prepareDestinationForModule( |
| 47 | moduleLoading: ModuleLoading, |
| 48 | nonce: ?string, |
| 49 | metadata: ClientReferenceMetadata, |
| 50 | ) { |
| 51 | prepareDestinationForModuleImpl(moduleLoading, metadata[0], nonce); |
| 52 | } |
| 53 | |
| 54 | export function resolveClientReference<T>( |
| 55 | bundlerConfig: ServerConsumerModuleMap, |
| 56 | metadata: ClientReferenceMetadata, |
| 57 | ): ClientReference<T> { |
| 58 | const baseURL = bundlerConfig; |
| 59 | return { |
| 60 | specifier: baseURL + metadata[0], |
| 61 | name: metadata[1], |
| 62 | }; |
| 63 | } |
| 64 | |
| 65 | export function resolveServerReference<T>( |
| 66 | config: ServerManifest, |
| 67 | id: ServerReferenceId, |
| 68 | ): ClientReference<T> { |
| 69 | const baseURL: string = config; |
| 70 | const idx = id.lastIndexOf('#'); |
| 71 | const exportName = id.slice(idx + 1); |
| 72 | const fullURL = id.slice(0, idx); |
| 73 | if (!fullURL.startsWith(baseURL)) { |
| 74 | throw new Error( |
| 75 | 'Attempted to load a Server Reference outside the hosted root.', |
| 76 | ); |
| 77 | } |
| 78 | return {specifier: fullURL, name: exportName}; |
| 79 | } |
| 80 | |
| 81 | const asyncModuleCache: Map<string, Thenable<any>> = new Map(); |
| 82 | |
| 83 | export function preloadModule<T>( |
| 84 | metadata: ClientReference<T>, |
| 85 | ): null | Thenable<any> { |
| 86 | const existingPromise = asyncModuleCache.get(metadata.specifier); |
| 87 | if (existingPromise) { |
| 88 | if (existingPromise.status === 'fulfilled') { |
| 89 | return null; |
| 90 | } |
| 91 | return existingPromise; |
| 92 | } else { |
| 93 | // $FlowFixMe[unsupported-syntax] |
| 94 | const modulePromise: Thenable<T> = import(metadata.specifier); |
| 95 | modulePromise.then( |
| 96 | value => { |
| 97 | const fulfilledThenable: FulfilledThenable<mixed> = |
| 98 | modulePromise as any; |
| 99 | fulfilledThenable.status = 'fulfilled'; |
| 100 | fulfilledThenable.value = value; |
| 101 | }, |
| 102 | reason => { |
| 103 | const rejectedThenable: RejectedThenable<mixed> = modulePromise as any; |
| 104 | rejectedThenable.status = 'rejected'; |
| 105 | rejectedThenable.reason = reason; |
| 106 | }, |
| 107 | ); |
| 108 | asyncModuleCache.set(metadata.specifier, modulePromise); |
| 109 | return modulePromise; |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | export function requireModule<T>(metadata: ClientReference<T>): T { |
| 114 | let moduleExports; |
| 115 | // We assume that preloadModule has been called before, which |
| 116 | // should have added something to the module cache. |
| 117 | const promise: any = asyncModuleCache.get(metadata.specifier); |
| 118 | if (promise.status === 'fulfilled') { |
| 119 | moduleExports = promise.value; |
| 120 | } else { |
| 121 | throw promise.reason; |
| 122 | } |
| 123 | return moduleExports[metadata.name]; |
| 124 | } |
| 125 | |
| 126 | // We cache ReactIOInfo across requests so that inner refreshes can dedupe with outer. |
| 127 | const moduleIOInfoCache: Map<string, ReactIOInfo> = __DEV__ |
| 128 | ? new Map() |
| 129 | : (null as any); |
| 130 | |
| 131 | export function getModuleDebugInfo<T>( |
| 132 | metadata: ClientReference<T>, |
| 133 | ): null | ReactDebugInfo { |
| 134 | if (!__DEV__) { |
| 135 | return null; |
| 136 | } |
| 137 | const filename = metadata.specifier; |
| 138 | let ioInfo = moduleIOInfoCache.get(filename); |
| 139 | if (ioInfo === undefined) { |
| 140 | let href; |
| 141 | try { |
| 142 | // $FlowFixMe[incompatible-type] |
| 143 | href = new URL(filename, document.baseURI).href; |
| 144 | } catch (_) { |
| 145 | href = filename; |
| 146 | } |
| 147 | let start = -1; |
| 148 | let end = -1; |
| 149 | let byteSize = 0; |
| 150 | // $FlowFixMe[method-unbinding] |
| 151 | if (typeof performance.getEntriesByType === 'function') { |
| 152 | // We may be able to collect the start and end time of this resource from Performance Observer. |
| 153 | const resourceEntries = performance.getEntriesByType('resource'); |
| 154 | for (let i = 0; i < resourceEntries.length; i++) { |
| 155 | const resourceEntry = resourceEntries[i]; |
| 156 | if (resourceEntry.name === href) { |
| 157 | start = resourceEntry.startTime; |
| 158 | end = start + resourceEntry.duration; |
| 159 | // $FlowFixMe[prop-missing] |
| 160 | byteSize = (resourceEntry.transferSize as any) || 0; |
| 161 | } |
| 162 | } |
| 163 | } |
| 164 | const value = Promise.resolve(href); |
| 165 | // $FlowFixMe[prop-missing] |
| 166 | value.status = 'fulfilled'; |
| 167 | // Is there some more useful representation for the chunk? |
| 168 | // $FlowFixMe[prop-missing] |
| 169 | value.value = href; |
| 170 | // Create a fake stack frame that points to the beginning of the chunk. This is |
| 171 | // probably not source mapped so will link to the compiled source rather than |
| 172 | // any individual file that goes into the chunks. |
| 173 | const fakeStack = new Error('react-stack-top-frame'); |
| 174 | if (fakeStack.stack.startsWith('Error: react-stack-top-frame')) { |
| 175 | // Looks like V8 |
| 176 | fakeStack.stack = |
| 177 | 'Error: react-stack-top-frame\n' + |
| 178 | // Add two frames since we always trim one off the top. |
| 179 | ' at Client Component Bundle (' + |
| 180 | href + |
| 181 | ':1:1)\n' + |
| 182 | ' at Client Component Bundle (' + |
| 183 | href + |
| 184 | ':1:1)'; |
| 185 | } else { |
| 186 | // Looks like Firefox or Safari. |
| 187 | // Add two frames since we always trim one off the top. |
| 188 | fakeStack.stack = |
| 189 | 'Client Component Bundle@' + |
| 190 | href + |
| 191 | ':1:1\n' + |
| 192 | 'Client Component Bundle@' + |
| 193 | href + |
| 194 | ':1:1'; |
| 195 | } |
| 196 | ioInfo = { |
| 197 | name: 'script', |
| 198 | start: start, |
| 199 | end: end, |
| 200 | value: value, |
| 201 | debugStack: fakeStack, |
| 202 | } as ReactIOInfo; |
| 203 | if (byteSize > 0) { |
| 204 | // $FlowFixMe[cannot-write] |
| 205 | ioInfo.byteSize = byteSize; |
| 206 | } |
| 207 | moduleIOInfoCache.set(filename, ioInfo); |
| 208 | } |
| 209 | // We could dedupe the async info too but conceptually each request is its own await. |
| 210 | const asyncInfo: ReactAsyncInfo = { |
| 211 | awaited: ioInfo, |
| 212 | }; |
| 213 | return [asyncInfo]; |
| 214 | } |