@expo/cli 0.10.7 → 0.10.9
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/build/bin/cli +2 -2
- package/build/src/register/registerAsync.js +2 -7
- package/build/src/register/registerAsync.js.map +1 -1
- package/build/src/start/interface/interactiveActions.js +2 -2
- package/build/src/start/interface/interactiveActions.js.map +1 -1
- package/build/src/start/server/BundlerDevServer.js +2 -2
- package/build/src/start/server/BundlerDevServer.js.map +1 -1
- package/build/src/start/server/metro/inspector-proxy/device.js +21 -4
- package/build/src/start/server/metro/inspector-proxy/device.js.map +1 -1
- package/build/src/start/server/metro/inspector-proxy/handlers/NetworkResponse.js.map +1 -1
- package/build/src/start/server/metro/inspector-proxy/handlers/PageReload.js.map +1 -1
- package/build/src/start/server/metro/inspector-proxy/handlers/VscodeDebuggerGetPossibleBreakpoints.js +22 -0
- package/build/src/start/server/metro/inspector-proxy/handlers/VscodeDebuggerGetPossibleBreakpoints.js.map +1 -0
- package/build/src/start/server/metro/inspector-proxy/handlers/VscodeDebuggerScriptParsed.js +55 -0
- package/build/src/start/server/metro/inspector-proxy/handlers/VscodeDebuggerScriptParsed.js.map +1 -0
- package/build/src/start/server/metro/inspector-proxy/handlers/VscodeDebuggerSetBreakpointByUrl.js +17 -0
- package/build/src/start/server/metro/inspector-proxy/handlers/VscodeDebuggerSetBreakpointByUrl.js.map +1 -0
- package/build/src/start/server/metro/inspector-proxy/handlers/VscodeRuntimeGetProperties.js +39 -0
- package/build/src/start/server/metro/inspector-proxy/handlers/VscodeRuntimeGetProperties.js.map +1 -0
- package/build/src/start/server/metro/inspector-proxy/handlers/types.js.map +1 -1
- package/build/src/start/server/metro/inspector-proxy/proxy.js +14 -6
- package/build/src/start/server/metro/inspector-proxy/proxy.js.map +1 -1
- package/build/src/start/server/metro/withMetroMultiPlatform.js +2 -1
- package/build/src/start/server/metro/withMetroMultiPlatform.js.map +1 -1
- package/build/src/start/server/middleware/ClassicManifestMiddleware.js +1 -1
- package/build/src/start/server/type-generation/__typetests__/fixtures/basic.js +38 -0
- package/build/src/start/server/type-generation/__typetests__/fixtures/basic.js.map +1 -0
- package/build/src/start/server/type-generation/__typetests__/generateFixtures.js +38 -0
- package/build/src/start/server/type-generation/__typetests__/generateFixtures.js.map +1 -0
- package/build/src/start/server/type-generation/__typetests__/route.test.js +165 -0
- package/build/src/start/server/type-generation/__typetests__/route.test.js.map +1 -0
- package/build/src/start/server/type-generation/routes.js +175 -62
- package/build/src/start/server/type-generation/routes.js.map +1 -1
- package/build/src/utils/analytics/rudderstackClient.js +2 -2
- package/build/src/utils/open.js +26 -0
- package/build/src/utils/open.js.map +1 -0
- package/package.json +11 -9
- package/build/src/start/server/metro/inspector-proxy/handlers/DebuggerScriptSource.js +0 -87
- package/build/src/start/server/metro/inspector-proxy/handlers/DebuggerScriptSource.js.map +0 -1
- package/build/src/start/server/metro/inspector-proxy/handlers/VscodeCompat.js +0 -63
- package/build/src/start/server/metro/inspector-proxy/handlers/VscodeCompat.js.map +0 -1
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
class VscodeRuntimeGetPropertiesHandler {
|
|
6
|
+
/** Keep track of `Runtime.getProperties` responses to intercept, by request id */ interceptGetProperties = new Set();
|
|
7
|
+
onDebuggerMessage(message, { debuggerType }) {
|
|
8
|
+
if (debuggerType === "vscode" && message.method === "Runtime.getProperties") {
|
|
9
|
+
this.interceptGetProperties.add(message.id);
|
|
10
|
+
}
|
|
11
|
+
// Do not block propagation of this message
|
|
12
|
+
return false;
|
|
13
|
+
}
|
|
14
|
+
onDeviceMessage(message, { debuggerType }) {
|
|
15
|
+
if (debuggerType === "vscode" && "id" in message && this.interceptGetProperties.has(message.id)) {
|
|
16
|
+
this.interceptGetProperties.delete(message.id);
|
|
17
|
+
var _result;
|
|
18
|
+
for (const item of (_result = message.result.result) != null ? _result : []){
|
|
19
|
+
var ref;
|
|
20
|
+
// Force-fully format the properties description to be an empty string
|
|
21
|
+
if (item.value) {
|
|
22
|
+
var _description;
|
|
23
|
+
item.value.description = (_description = item.value.description) != null ? _description : "";
|
|
24
|
+
}
|
|
25
|
+
// Avoid passing the `objectId` for symbol types.
|
|
26
|
+
// When collapsing in vscode, it will fetch information about the symbol using the `objectId`.
|
|
27
|
+
// The `Runtime.getProperties` request of the symbol hard-crashes Hermes.
|
|
28
|
+
if (((ref = item.value) == null ? void 0 : ref.type) === "symbol" && item.value.objectId) {
|
|
29
|
+
delete item.value.objectId;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
// Do not block propagation of this message
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
exports.VscodeRuntimeGetPropertiesHandler = VscodeRuntimeGetPropertiesHandler;
|
|
38
|
+
|
|
39
|
+
//# sourceMappingURL=VscodeRuntimeGetProperties.js.map
|
package/build/src/start/server/metro/inspector-proxy/handlers/VscodeRuntimeGetProperties.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../src/start/server/metro/inspector-proxy/handlers/VscodeRuntimeGetProperties.ts"],"sourcesContent":["import Protocol from 'devtools-protocol';\n\nimport { ExpoDebuggerInfo } from '../device';\nimport { CdpMessage, DebuggerRequest, DeviceResponse, InspectorHandler } from './types';\n\n/**\n * Vscode doesn't seem to work nicely with missing `description` fields on `RemoteObject` instances.\n * It also tries to invoke `Runtime.callFunctionOn` on `Symbol` types, which crashes Hermes.\n * This handler tries to compensate for these two separate issues.\n *\n * @see https://github.com/facebook/hermes/issues/114\n * @see https://github.com/microsoft/vscode-js-debug/issues/1583\n */\nexport class VscodeRuntimeGetPropertiesHandler implements InspectorHandler {\n /** Keep track of `Runtime.getProperties` responses to intercept, by request id */\n interceptGetProperties = new Set<number>();\n\n onDebuggerMessage(\n message: DebuggerRequest<RuntimeGetProperties>,\n { debuggerType }: ExpoDebuggerInfo\n ): boolean {\n if (debuggerType === 'vscode' && message.method === 'Runtime.getProperties') {\n this.interceptGetProperties.add(message.id);\n }\n\n // Do not block propagation of this message\n return false;\n }\n\n onDeviceMessage(\n message: DeviceResponse<RuntimeGetProperties>,\n { debuggerType }: ExpoDebuggerInfo\n ) {\n if (\n debuggerType === 'vscode' &&\n 'id' in message &&\n this.interceptGetProperties.has(message.id)\n ) {\n this.interceptGetProperties.delete(message.id);\n\n for (const item of message.result.result ?? []) {\n // Force-fully format the properties description to be an empty string\n if (item.value) {\n item.value.description = item.value.description ?? '';\n }\n\n // Avoid passing the `objectId` for symbol types.\n // When collapsing in vscode, it will fetch information about the symbol using the `objectId`.\n // The `Runtime.getProperties` request of the symbol hard-crashes Hermes.\n if (item.value?.type === 'symbol' && item.value.objectId) {\n delete item.value.objectId;\n }\n }\n }\n\n // Do not block propagation of this message\n return false;\n }\n}\n\n/** @see https://chromedevtools.github.io/devtools-protocol/v8/Runtime/#method-getProperties */\nexport type RuntimeGetProperties = CdpMessage<\n 'Runtime.getProperties',\n Protocol.Runtime.GetPropertiesRequest,\n Protocol.Runtime.GetPropertiesResponse\n>;\n"],"names":["VscodeRuntimeGetPropertiesHandler","interceptGetProperties","Set","onDebuggerMessage","message","debuggerType","method","add","id","onDeviceMessage","has","delete","item","result","value","description","type","objectId"],"mappings":"AAAA;;;;AAaO,MAAMA,iCAAiC;IAC5C,kFAAkF,CAClFC,sBAAsB,GAAG,IAAIC,GAAG,EAAU,CAAC;IAE3CC,iBAAiB,CACfC,OAA8C,EAC9C,EAAEC,YAAY,CAAA,EAAoB,EACzB;QACT,IAAIA,YAAY,KAAK,QAAQ,IAAID,OAAO,CAACE,MAAM,KAAK,uBAAuB,EAAE;YAC3E,IAAI,CAACL,sBAAsB,CAACM,GAAG,CAACH,OAAO,CAACI,EAAE,CAAC,CAAC;SAC7C;QAED,2CAA2C;QAC3C,OAAO,KAAK,CAAC;KACd;IAEDC,eAAe,CACbL,OAA6C,EAC7C,EAAEC,YAAY,CAAA,EAAoB,EAClC;QACA,IACEA,YAAY,KAAK,QAAQ,IACzB,IAAI,IAAID,OAAO,IACf,IAAI,CAACH,sBAAsB,CAACS,GAAG,CAACN,OAAO,CAACI,EAAE,CAAC,EAC3C;YACA,IAAI,CAACP,sBAAsB,CAACU,MAAM,CAACP,OAAO,CAACI,EAAE,CAAC,CAAC;gBAE5BJ,OAAqB;YAAxC,KAAK,MAAMQ,IAAI,IAAIR,CAAAA,OAAqB,GAArBA,OAAO,CAACS,MAAM,CAACA,MAAM,YAArBT,OAAqB,GAAI,EAAE,CAAE;oBAS1CQ,GAAU;gBARd,sEAAsE;gBACtE,IAAIA,IAAI,CAACE,KAAK,EAAE;wBACWF,YAAsB;oBAA/CA,IAAI,CAACE,KAAK,CAACC,WAAW,GAAGH,CAAAA,YAAsB,GAAtBA,IAAI,CAACE,KAAK,CAACC,WAAW,YAAtBH,YAAsB,GAAI,EAAE,CAAC;iBACvD;gBAED,iDAAiD;gBACjD,8FAA8F;gBAC9F,yEAAyE;gBACzE,IAAIA,CAAAA,CAAAA,GAAU,GAAVA,IAAI,CAACE,KAAK,SAAM,GAAhBF,KAAAA,CAAgB,GAAhBA,GAAU,CAAEI,IAAI,CAAA,KAAK,QAAQ,IAAIJ,IAAI,CAACE,KAAK,CAACG,QAAQ,EAAE;oBACxD,OAAOL,IAAI,CAACE,KAAK,CAACG,QAAQ,CAAC;iBAC5B;aACF;SACF;QAED,2CAA2C;QAC3C,OAAO,KAAK,CAAC;KACd;CACF;QA7CYjB,iCAAiC,GAAjCA,iCAAiC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../src/start/server/metro/inspector-proxy/handlers/types.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../../../../../../src/start/server/metro/inspector-proxy/handlers/types.ts"],"sourcesContent":["import { ExpoDebuggerInfo } from '../device';\n\nexport interface InspectorHandler {\n /**\n * Intercept a message coming from the device, modify or respond to it through `this._sendMessageToDevice`.\n * Return `true` if the message was handled, this will stop the message propagation.\n */\n onDeviceMessage?(message: DeviceRequest | DeviceResponse, info: ExpoDebuggerInfo): boolean;\n\n /**\n * Intercept a message coming from the debugger, modify or respond to it through `socket.send`.\n * Return `true` if the message was handled, this will stop the message propagation.\n */\n onDebuggerMessage?(message: DebuggerRequest, info: ExpoDebuggerInfo): boolean;\n}\n\n/**\n * The outline of a basic Chrome DevTools Protocol request, either from device or debugger.\n * Both the request and response parameters could be optional, use `never` to enforce these fields.\n */\nexport type CdpMessage<\n Method extends string = string,\n Request extends object = object,\n Response extends object = object\n> = {\n id: number;\n method: Method;\n params: Request;\n result: Response;\n};\n\nexport type DeviceRequest<M extends CdpMessage = CdpMessage> = Pick<M, 'method' | 'params'>;\nexport type DeviceResponse<M extends CdpMessage = CdpMessage> = Pick<M, 'id' | 'result'>;\n\nexport type DebuggerRequest<M extends CdpMessage = CdpMessage> = Pick<\n M,\n 'id' | 'method' | 'params'\n>;\nexport type DebuggerResponse<M extends CdpMessage = CdpMessage> = Pick<M, 'result'>;\n"],"names":[],"mappings":"AAAA"}
|
|
@@ -62,7 +62,7 @@ class ExpoInspectorProxy {
|
|
|
62
62
|
wss.on("connection", (socket, request)=>{
|
|
63
63
|
try {
|
|
64
64
|
const fallbackDeviceId = String(this.metroProxy._deviceCounter++);
|
|
65
|
-
const { deviceId: newDeviceId , deviceName , appName } =
|
|
65
|
+
const { deviceId: newDeviceId , deviceName , appName } = getDeviceInfo(request.url);
|
|
66
66
|
const deviceId = newDeviceId != null ? newDeviceId : fallbackDeviceId;
|
|
67
67
|
const oldDevice = this.devices.get(deviceId);
|
|
68
68
|
const newDevice = new this.DeviceClass(deviceId, deviceName, appName, socket, this.metroProxy._projectRoot);
|
|
@@ -104,7 +104,7 @@ class ExpoInspectorProxy {
|
|
|
104
104
|
// See: https://github.com/facebook/metro/blob/eeb211fdcfdcb9e7f8a51721bd0f48bc7d0d211f/packages/metro-inspector-proxy/src/InspectorProxy.js#L193
|
|
105
105
|
wss.on("connection", (socket, request)=>{
|
|
106
106
|
try {
|
|
107
|
-
const { deviceId , pageId } =
|
|
107
|
+
const { deviceId , pageId , debuggerType } = getDebuggerInfo(request.url);
|
|
108
108
|
if (!deviceId || !pageId) {
|
|
109
109
|
// TODO(cedric): change these errors to proper error types
|
|
110
110
|
throw new Error(`Missing "device" and/or "page" IDs in query parameters`);
|
|
@@ -115,7 +115,13 @@ class ExpoInspectorProxy {
|
|
|
115
115
|
throw new Error(`Device with ID "${deviceId}" not found.`);
|
|
116
116
|
}
|
|
117
117
|
debug("New debugger connected: device=%s, app=%s", device._name, device._app);
|
|
118
|
-
device
|
|
118
|
+
// @ts-expect-error The `handleDebuggerConnectionWithType` is part of our device implementation, not Metro's device
|
|
119
|
+
if (debuggerType && typeof device.handleDebuggerConnectionWithType === "function") {
|
|
120
|
+
// @ts-expect-error The `handleDebuggerConnectionWithType` is part of our device implementation, not Metro's device
|
|
121
|
+
device.handleDebuggerConnectionWithType(socket, pageId, debuggerType);
|
|
122
|
+
} else {
|
|
123
|
+
device.handleDebuggerConnection(socket, pageId);
|
|
124
|
+
}
|
|
119
125
|
socket.on("close", ()=>{
|
|
120
126
|
debug("Debugger disconnected: device=%s, app=%s", device._name, device._app);
|
|
121
127
|
});
|
|
@@ -139,7 +145,7 @@ exports.ExpoInspectorProxy = ExpoInspectorProxy;
|
|
|
139
145
|
function asString(value = "") {
|
|
140
146
|
return Array.isArray(value) ? value.join() : value;
|
|
141
147
|
}
|
|
142
|
-
function
|
|
148
|
+
function getDeviceInfo(url) {
|
|
143
149
|
const { query } = (0, _url).parse(url != null ? url : "", true);
|
|
144
150
|
return {
|
|
145
151
|
deviceId: asString(query.device) || undefined,
|
|
@@ -147,11 +153,13 @@ function getNewDeviceInfo(url) {
|
|
|
147
153
|
appName: asString(query.app) || "Unknown app name"
|
|
148
154
|
};
|
|
149
155
|
}
|
|
150
|
-
function
|
|
156
|
+
function getDebuggerInfo(url) {
|
|
151
157
|
const { query } = (0, _url).parse(url != null ? url : "", true);
|
|
158
|
+
var ref;
|
|
152
159
|
return {
|
|
153
160
|
deviceId: asString(query.device),
|
|
154
|
-
pageId: asString(query.page)
|
|
161
|
+
pageId: asString(query.page),
|
|
162
|
+
debuggerType: (ref = asString(query.type)) != null ? ref : undefined
|
|
155
163
|
};
|
|
156
164
|
}
|
|
157
165
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../src/start/server/metro/inspector-proxy/proxy.ts"],"sourcesContent":["import type { Server as HttpServer, IncomingMessage, ServerResponse } from 'http';\nimport type { Server as HttpsServer } from 'https';\nimport type { InspectorProxy as MetroProxy, Device as MetroDevice } from 'metro-inspector-proxy';\nimport { parse } from 'url';\nimport WS, { Server as WSServer } from 'ws';\n\nimport { Log } from '../../../../log';\n\nconst WS_DEVICE_URL = '/inspector/device';\nconst WS_DEBUGGER_URL = '/inspector/debug';\nconst WS_GENERIC_ERROR_STATUS = 1011;\n\nconst debug = require('debug')('expo:metro:inspector-proxy:proxy') as typeof console.log;\n\n// This is a workaround for `ConstructorType` not working on dynamically generated classes\ntype Instantiatable<Instance> = new (...args: any) => Instance;\n\nexport class ExpoInspectorProxy<D extends MetroDevice = MetroDevice> {\n constructor(\n public readonly metroProxy: MetroProxy,\n private DeviceClass: Instantiatable<D>,\n public readonly devices: Map<string, D> = new Map()\n ) {\n // monkey-patch the device list to expose it within the metro inspector\n // See https://github.com/facebook/metro/pull/991\n // @ts-expect-error - Device ID is changing from `number` to `string`\n this.metroProxy._devices = this.devices;\n\n // force httpEndpointMiddleware to be bound to this proxy instance\n this.processRequest = this.processRequest.bind(this);\n }\n\n /**\n * Initialize the server address from the metro server.\n * This is required to properly reference sourcemaps for the debugger.\n */\n private setServerAddress(server: HttpServer | HttpsServer) {\n const addressInfo = server.address();\n\n if (typeof addressInfo === 'string') {\n throw new Error(`Inspector proxy could not resolve the server address, got \"${addressInfo}\"`);\n } else if (addressInfo === null) {\n throw new Error(`Inspector proxy could not resolve the server address, got \"null\"`);\n }\n\n const { address, port, family } = addressInfo;\n\n if (family === 'IPv6') {\n this.metroProxy._serverAddressWithPort = `[${address ?? '::1'}]:${port}`;\n } else {\n this.metroProxy._serverAddressWithPort = `${address ?? 'localhost'}:${port}`;\n }\n }\n\n /** @see https://chromedevtools.github.io/devtools-protocol/#endpoints */\n public processRequest(req: IncomingMessage, res: ServerResponse, next: (error?: Error) => any) {\n this.metroProxy.processRequest(req, res, next);\n }\n\n public createWebSocketListeners(server: HttpServer | HttpsServer): Record<string, WSServer> {\n this.setServerAddress(server);\n\n return {\n [WS_DEVICE_URL]: this.createDeviceWebSocketServer(),\n [WS_DEBUGGER_URL]: this.createDebuggerWebSocketServer(),\n };\n }\n\n private createDeviceWebSocketServer() {\n const wss = new WS.Server({\n noServer: true,\n perMessageDeflate: false,\n });\n\n // See: https://github.com/facebook/metro/blob/eeb211fdcfdcb9e7f8a51721bd0f48bc7d0d211f/packages/metro-inspector-proxy/src/InspectorProxy.js#L157\n wss.on('connection', (socket, request) => {\n try {\n const fallbackDeviceId = String(this.metroProxy._deviceCounter++);\n const { deviceId: newDeviceId, deviceName, appName } = getNewDeviceInfo(request.url);\n\n const deviceId = newDeviceId ?? fallbackDeviceId;\n\n const oldDevice = this.devices.get(deviceId);\n const newDevice = new this.DeviceClass(\n deviceId,\n deviceName,\n appName,\n socket,\n this.metroProxy._projectRoot\n );\n\n if (oldDevice) {\n debug('Device reconnected: device=%s, app=%s, id=%s', deviceName, appName, deviceId);\n // See: https://github.com/facebook/metro/pull/991\n // @ts-expect-error - Newly introduced method coming to metro-inspector-proxy soon\n oldDevice.handleDuplicateDeviceConnection(newDevice);\n } else {\n debug('New device connected: device=%s, app=%s, id=%s', deviceName, appName, deviceId);\n }\n\n this.devices.set(deviceId, newDevice);\n\n socket.on('close', () => {\n if (this.devices.get(deviceId) === newDevice) {\n this.devices.delete(deviceId);\n debug('Device disconnected: device=%s, app=%s, id=%s', deviceName, appName, deviceId);\n }\n });\n } catch (error: unknown) {\n let message = '';\n\n debug('Could not establish a connection to on-device debugger:', error);\n\n if (error instanceof Error) {\n message = error.toString();\n Log.error('Failed to create a socket connection to on-device debugger (Hermes engine).');\n Log.exception(error);\n } else {\n Log.error(\n 'Failed to create a socket connection to on-device debugger (Hermes engine), unknown error.'\n );\n }\n\n socket.close(WS_GENERIC_ERROR_STATUS, message || 'Unknown error');\n }\n });\n\n return wss;\n }\n\n private createDebuggerWebSocketServer() {\n const wss = new WS.Server({\n noServer: true,\n perMessageDeflate: false,\n });\n\n // See: https://github.com/facebook/metro/blob/eeb211fdcfdcb9e7f8a51721bd0f48bc7d0d211f/packages/metro-inspector-proxy/src/InspectorProxy.js#L193\n wss.on('connection', (socket, request) => {\n try {\n const { deviceId, pageId } = getExistingDeviceInfo(request.url);\n if (!deviceId || !pageId) {\n // TODO(cedric): change these errors to proper error types\n throw new Error(`Missing \"device\" and/or \"page\" IDs in query parameters`);\n }\n\n const device = this.devices.get(deviceId);\n if (!device) {\n // TODO(cedric): change these errors to proper error types\n throw new Error(`Device with ID \"${deviceId}\" not found.`);\n }\n\n debug('New debugger connected: device=%s, app=%s', device._name, device._app);\n\n device.handleDebuggerConnection(socket, pageId);\n\n socket.on('close', () => {\n debug('Debugger disconnected: device=%s, app=%s', device._name, device._app);\n });\n } catch (error: unknown) {\n let message = '';\n\n debug('Could not establish a connection to debugger:', error);\n\n if (error instanceof Error) {\n message = error.toString();\n Log.error('Failed to create a socket connection to the debugger.');\n Log.exception(error);\n } else {\n Log.error('Failed to create a socket connection to the debugger, unkown error.');\n }\n\n socket.close(WS_GENERIC_ERROR_STATUS, message || 'Unknown error');\n }\n });\n\n return wss;\n }\n}\n\nfunction asString(value: string | string[] = ''): string {\n return Array.isArray(value) ? value.join() : value;\n}\n\nfunction getNewDeviceInfo(url: IncomingMessage['url']) {\n const { query } = parse(url ?? '', true);\n return {\n deviceId: asString(query.device) || undefined,\n deviceName: asString(query.name) || 'Unknown device name',\n appName: asString(query.app) || 'Unknown app name',\n };\n}\n\nfunction getExistingDeviceInfo(url: IncomingMessage['url']) {\n const { query } = parse(url ?? '', true);\n return {\n deviceId: asString(query.device),\n pageId: asString(query.page),\n };\n}\n"],"names":["WS_DEVICE_URL","WS_DEBUGGER_URL","WS_GENERIC_ERROR_STATUS","debug","require","ExpoInspectorProxy","constructor","metroProxy","DeviceClass","devices","Map","_devices","processRequest","bind","setServerAddress","server","addressInfo","address","Error","port","family","_serverAddressWithPort","req","res","next","createWebSocketListeners","createDeviceWebSocketServer","createDebuggerWebSocketServer","wss","WS","Server","noServer","perMessageDeflate","on","socket","request","fallbackDeviceId","String","_deviceCounter","deviceId","newDeviceId","deviceName","appName","getNewDeviceInfo","url","oldDevice","get","newDevice","_projectRoot","handleDuplicateDeviceConnection","set","delete","error","message","toString","Log","exception","close","pageId","getExistingDeviceInfo","device","_name","_app","handleDebuggerConnection","asString","value","Array","isArray","join","query","parse","undefined","name","app","page"],"mappings":"AAAA;;;;AAGsB,IAAA,IAAK,WAAL,KAAK,CAAA;AACY,IAAA,GAAI,kCAAJ,IAAI,EAAA;AAEvB,IAAA,IAAiB,WAAjB,iBAAiB,CAAA;;;;;;AAErC,MAAMA,aAAa,GAAG,mBAAmB,AAAC;AAC1C,MAAMC,eAAe,GAAG,kBAAkB,AAAC;AAC3C,MAAMC,uBAAuB,GAAG,IAAI,AAAC;AAErC,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,kCAAkC,CAAC,AAAsB,AAAC;AAKlF,MAAMC,kBAAkB;IAC7BC,YACkBC,UAAsB,EAC9BC,WAA8B,EACtBC,OAAuB,GAAG,IAAIC,GAAG,EAAE,CACnD;aAHgBH,UAAsB,GAAtBA,UAAsB;aAC9BC,WAA8B,GAA9BA,WAA8B;aACtBC,OAAuB,GAAvBA,OAAuB;QAEvC,uEAAuE;QACvE,iDAAiD;QACjD,qEAAqE;QACr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AAC;iBAClF;gBAEDlB,MAAM,CAACuB,KAAK,CAACvD,uBAAuB,EAAEmD,OAAO,IAAI,eAAe,CAAC,CAAC;aACnE;SACF,CAAC,CAAC;QAEH,OAAOzB,GAAG,CAAC;KACZ;CACF;QAhKYvB,kBAAkB,GAAlBA,kBAAkB;AAkK/B,SAAS2D,QAAQ,CAACC,KAAwB,GAAG,EAAE,EAAU;IACvD,OAAOC,KAAK,CAACC,OAAO,CAACF,KAAK,CAAC,GAAGA,KAAK,CAACG,IAAI,EAAE,GAAGH,KAAK,CAAC;CACpD;AAED,SAAStB,gBAAgB,CAACC,GAA2B,EAAE;IACrD,MAAM,EAAEyB,KAAK,CAAA,EAAE,GAAGC,CAAAA,GAAAA,IAAK,AAAiB,CAAA,MAAjB,CAAC1B,GAAG,WAAHA,GAAG,GAAI,EAAE,EAAE,IAAI,CAAC,AAAC;IACzC,OAAO;QACLL,QAAQ,EAAEyB,QAAQ,CAACK,KAAK,CAACT,MAAM,CAAC,IAAIW,SAAS;QAC7C9B,UAAU,EAAEuB,QAAQ,CAACK,KAAK,CAACG,IAAI,CAAC,IAAI,qBAAqB;QACzD9B,OAAO,EAAEsB,QAAQ,CAACK,KAAK,CAACI,GAAG,CAAC,IAAI,kBAAkB;KACnD,CAAC;CACH;AAED,SAASd,qBAAqB,CAACf,GAA2B,EAAE;IAC1D,MAAM,EAAEyB,KAAK,CAAA,EAAE,GAAGC,CAAAA,GAAAA,IAAK,AAAiB,CAAA,MAAjB,CAAC1B,GAAG,WAAHA,GAAG,GAAI,EAAE,EAAE,IAAI,CAAC,AAAC;IACzC,OAAO;QACLL,QAAQ,EAAEyB,QAAQ,CAACK,KAAK,CAACT,MAAM,CAAC;QAChCF,MAAM,EAAEM,QAAQ,CAACK,KAAK,CAACK,IAAI,CAAC;KAC7B,CAAC;CACH"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../src/start/server/metro/inspector-proxy/proxy.ts"],"sourcesContent":["import type { Server as HttpServer, IncomingMessage, ServerResponse } from 'http';\nimport type { Server as HttpsServer } from 'https';\nimport type { InspectorProxy as MetroProxy, Device as MetroDevice } from 'metro-inspector-proxy';\nimport { parse } from 'url';\nimport WS, { Server as WSServer } from 'ws';\n\nimport { Log } from '../../../../log';\n\nconst WS_DEVICE_URL = '/inspector/device';\nconst WS_DEBUGGER_URL = '/inspector/debug';\nconst WS_GENERIC_ERROR_STATUS = 1011;\n\nconst debug = require('debug')('expo:metro:inspector-proxy:proxy') as typeof console.log;\n\n// This is a workaround for `ConstructorType` not working on dynamically generated classes\ntype Instantiatable<Instance> = new (...args: any) => Instance;\n\nexport class ExpoInspectorProxy<D extends MetroDevice = MetroDevice> {\n constructor(\n public readonly metroProxy: MetroProxy,\n private DeviceClass: Instantiatable<D>,\n public readonly devices: Map<string, D> = new Map()\n ) {\n // monkey-patch the device list to expose it within the metro inspector\n // See https://github.com/facebook/metro/pull/991\n // @ts-expect-error - Device ID is changing from `number` to `string`\n this.metroProxy._devices = this.devices;\n\n // force httpEndpointMiddleware to be bound to this proxy instance\n this.processRequest = this.processRequest.bind(this);\n }\n\n /**\n * Initialize the server address from the metro server.\n * This is required to properly reference sourcemaps for the debugger.\n */\n private setServerAddress(server: HttpServer | HttpsServer) {\n const addressInfo = server.address();\n\n if (typeof addressInfo === 'string') {\n throw new Error(`Inspector proxy could not resolve the server address, got \"${addressInfo}\"`);\n } else if (addressInfo === null) {\n throw new Error(`Inspector proxy could not resolve the server address, got \"null\"`);\n }\n\n const { address, port, family } = addressInfo;\n\n if (family === 'IPv6') {\n this.metroProxy._serverAddressWithPort = `[${address ?? '::1'}]:${port}`;\n } else {\n this.metroProxy._serverAddressWithPort = `${address ?? 'localhost'}:${port}`;\n }\n }\n\n /** @see https://chromedevtools.github.io/devtools-protocol/#endpoints */\n public processRequest(req: IncomingMessage, res: ServerResponse, next: (error?: Error) => any) {\n this.metroProxy.processRequest(req, res, next);\n }\n\n public createWebSocketListeners(server: HttpServer | HttpsServer): Record<string, WSServer> {\n this.setServerAddress(server);\n\n return {\n [WS_DEVICE_URL]: this.createDeviceWebSocketServer(),\n [WS_DEBUGGER_URL]: this.createDebuggerWebSocketServer(),\n };\n }\n\n private createDeviceWebSocketServer() {\n const wss = new WS.Server({\n noServer: true,\n perMessageDeflate: false,\n });\n\n // See: https://github.com/facebook/metro/blob/eeb211fdcfdcb9e7f8a51721bd0f48bc7d0d211f/packages/metro-inspector-proxy/src/InspectorProxy.js#L157\n wss.on('connection', (socket, request) => {\n try {\n const fallbackDeviceId = String(this.metroProxy._deviceCounter++);\n const { deviceId: newDeviceId, deviceName, appName } = getDeviceInfo(request.url);\n\n const deviceId = newDeviceId ?? fallbackDeviceId;\n\n const oldDevice = this.devices.get(deviceId);\n const newDevice = new this.DeviceClass(\n deviceId,\n deviceName,\n appName,\n socket,\n this.metroProxy._projectRoot\n );\n\n if (oldDevice) {\n debug('Device reconnected: device=%s, app=%s, id=%s', deviceName, appName, deviceId);\n // See: https://github.com/facebook/metro/pull/991\n // @ts-expect-error - Newly introduced method coming to metro-inspector-proxy soon\n oldDevice.handleDuplicateDeviceConnection(newDevice);\n } else {\n debug('New device connected: device=%s, app=%s, id=%s', deviceName, appName, deviceId);\n }\n\n this.devices.set(deviceId, newDevice);\n\n socket.on('close', () => {\n if (this.devices.get(deviceId) === newDevice) {\n this.devices.delete(deviceId);\n debug('Device disconnected: device=%s, app=%s, id=%s', deviceName, appName, deviceId);\n }\n });\n } catch (error: unknown) {\n let message = '';\n\n debug('Could not establish a connection to on-device debugger:', error);\n\n if (error instanceof Error) {\n message = error.toString();\n Log.error('Failed to create a socket connection to on-device debugger (Hermes engine).');\n Log.exception(error);\n } else {\n Log.error(\n 'Failed to create a socket connection to on-device debugger (Hermes engine), unknown error.'\n );\n }\n\n socket.close(WS_GENERIC_ERROR_STATUS, message || 'Unknown error');\n }\n });\n\n return wss;\n }\n\n private createDebuggerWebSocketServer() {\n const wss = new WS.Server({\n noServer: true,\n perMessageDeflate: false,\n });\n\n // See: https://github.com/facebook/metro/blob/eeb211fdcfdcb9e7f8a51721bd0f48bc7d0d211f/packages/metro-inspector-proxy/src/InspectorProxy.js#L193\n wss.on('connection', (socket, request) => {\n try {\n const { deviceId, pageId, debuggerType } = getDebuggerInfo(request.url);\n if (!deviceId || !pageId) {\n // TODO(cedric): change these errors to proper error types\n throw new Error(`Missing \"device\" and/or \"page\" IDs in query parameters`);\n }\n\n const device = this.devices.get(deviceId);\n if (!device) {\n // TODO(cedric): change these errors to proper error types\n throw new Error(`Device with ID \"${deviceId}\" not found.`);\n }\n\n debug('New debugger connected: device=%s, app=%s', device._name, device._app);\n\n // @ts-expect-error The `handleDebuggerConnectionWithType` is part of our device implementation, not Metro's device\n if (debuggerType && typeof device.handleDebuggerConnectionWithType === 'function') {\n // @ts-expect-error The `handleDebuggerConnectionWithType` is part of our device implementation, not Metro's device\n device.handleDebuggerConnectionWithType(socket, pageId, debuggerType);\n } else {\n device.handleDebuggerConnection(socket, pageId);\n }\n\n socket.on('close', () => {\n debug('Debugger disconnected: device=%s, app=%s', device._name, device._app);\n });\n } catch (error: unknown) {\n let message = '';\n\n debug('Could not establish a connection to debugger:', error);\n\n if (error instanceof Error) {\n message = error.toString();\n Log.error('Failed to create a socket connection to the debugger.');\n Log.exception(error);\n } else {\n Log.error('Failed to create a socket connection to the debugger, unkown error.');\n }\n\n socket.close(WS_GENERIC_ERROR_STATUS, message || 'Unknown error');\n }\n });\n\n return wss;\n }\n}\n\nfunction asString(value: string | string[] = ''): string {\n return Array.isArray(value) ? value.join() : value;\n}\n\nfunction getDeviceInfo(url: IncomingMessage['url']) {\n const { query } = parse(url ?? '', true);\n return {\n deviceId: asString(query.device) || undefined,\n deviceName: asString(query.name) || 'Unknown device name',\n appName: asString(query.app) || 'Unknown app name',\n };\n}\n\nfunction getDebuggerInfo(url: IncomingMessage['url']) {\n const { query } = parse(url ?? '', true);\n return {\n deviceId: asString(query.device),\n pageId: asString(query.page),\n debuggerType: asString(query.type) ?? undefined,\n };\n}\n"],"names":["WS_DEVICE_URL","WS_DEBUGGER_URL","WS_GENERIC_ERROR_STATUS","debug","require","ExpoInspectorProxy","constructor","metroProxy","DeviceClass","devices","Map","_devices","processRequest","bind","setServerAddress","server","addressInfo","address","Error","port","family","_serverAddressWithPort","req","res","next","createWebSocketListeners","createDeviceWebSocketServer","createDebuggerWebSocketServer","wss","WS","Server","noServer","perMessageDeflate","on","socket","request","fallbackDeviceId","String","_deviceCounter","deviceId","newDeviceId","deviceName","appName","getDeviceInfo","url","oldDevice","get","newDevice","_projectRoot","handleDuplicateDeviceConnection","set","delete","error","message","toString","Log","exception","close","pageId","debuggerType","getDebuggerInfo","device","_name","_app","handleDebuggerConnectionWithType","handleDebuggerConnection","asString","value","Array","isArray","join","query","parse","undefined","name","app","page","type"],"mappings":"AAAA;;;;AAGsB,IAAA,IAAK,WAAL,KAAK,CAAA;AACY,IAAA,GAAI,kCAAJ,IAAI,EAAA;AAEvB,IAAA,IAAiB,WAAjB,iBAAiB,CAAA;;;;;;AAErC,MAAMA,aAAa,GAAG,mBAAmB,AAAC;AAC1C,MAAMC,eAAe,GAAG,kBAAkB,AAAC;AAC3C,MAAMC,uBAAuB,GAAG,IAAI,AAAC;AAErC,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,kCAAkC,CAAC,AAAsB,AAAC;AAKlF,MAAMC,kBAAkB;IAC7BC,YACkBC,UAAsB,EAC9BC,WAA8B,EACtBC,OAAuB,GAAG,IAAIC,GAAG,EAAE,CACnD;aAHgBH,UAAsB,GAAtBA,UAAsB;aAC9BC,WAA8B,GAA9BA,WAA8B;aACtBC,OAAuB,GAAvBA,OAAuB;QAEvC,uEAAuE;QACvE,iDAAiD;QACjD,qEAAqE;QACrE,IAAI,CAACF,UAAU,CAACI,QAAQ,GAAG,IAAI,CAACF,OAAO,CAAC;QAExC,kEAAkE;QAClE,IAAI,CAACG,cAAc,GAAG,IAAI,CAACA,cAAc,CAACC,IAAI,CAAC,IAAI,CAAC,CA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,QAAQ,CAACK,KAAK,CAACM,IAAI,CAAC,YAApBX,GAAoB,GAAIO,SAAS;KAChD,CAAC;CACH"}
|
|
@@ -13,6 +13,7 @@ var _log = require("../../../log");
|
|
|
13
13
|
var _fileNotifier = require("../../../utils/FileNotifier");
|
|
14
14
|
var _env = require("../../../utils/env");
|
|
15
15
|
var _exit = require("../../../utils/exit");
|
|
16
|
+
var _interactive = require("../../../utils/interactive");
|
|
16
17
|
var _link = require("../../../utils/link");
|
|
17
18
|
var _loadTsConfigPaths = require("../../../utils/tsconfig/loadTsConfigPaths");
|
|
18
19
|
var _resolveWithTsConfigPaths = require("../../../utils/tsconfig/resolveWithTsConfigPaths");
|
|
@@ -91,7 +92,7 @@ function withExtendedResolver(config, { projectRoot , tsconfig , platforms , isT
|
|
|
91
92
|
paths: (_paths1 = tsconfig.paths) != null ? _paths1 : {},
|
|
92
93
|
baseUrl: tsconfig.baseUrl
|
|
93
94
|
}) : null;
|
|
94
|
-
if (isTsconfigPathsEnabled &&
|
|
95
|
+
if (isTsconfigPathsEnabled && (0, _interactive).isInteractive()) {
|
|
95
96
|
// TODO: We should track all the files that used imports and invalidate them
|
|
96
97
|
// currently the user will need to save all the files that use imports to
|
|
97
98
|
// use the new aliases.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/withMetroMultiPlatform.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport { ConfigT } from 'metro-config';\nimport { Resolution, ResolutionContext } from 'metro-resolver';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { Log } from '../../../log';\nimport { FileNotifier } from '../../../utils/FileNotifier';\nimport { env } from '../../../utils/env';\nimport { installExitHooks } from '../../../utils/exit';\nimport { learnMore } from '../../../utils/link';\nimport { loadTsConfigPathsAsync, TsConfigPaths } from '../../../utils/tsconfig/loadTsConfigPaths';\nimport { resolveWithTsConfigPaths } from '../../../utils/tsconfig/resolveWithTsConfigPaths';\nimport { WebSupportProjectPrerequisite } from '../../doctor/web/WebSupportProjectPrerequisite';\nimport { PlatformBundlers } from '../platformBundlers';\nimport {\n EXTERNAL_REQUIRE_NATIVE_POLYFILL,\n EXTERNAL_REQUIRE_POLYFILL,\n getNodeExternalModuleId,\n isNodeExternal,\n setupNodeExternals,\n} from './externals';\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport { importMetroResolverFromProject } from './resolveFromProject';\nimport { getAppRouterRelativeEntryPath } from './router';\nimport { withMetroResolvers } from './withMetroResolvers';\n\ntype Mutable<T> = { -readonly [K in keyof T]: T[K] };\n\nconst debug = require('debug')('expo:start:server:metro:multi-platform') as typeof console.log;\n\nfunction withWebPolyfills(config: ConfigT, projectRoot: string): ConfigT {\n const originalGetPolyfills = config.serializer.getPolyfills\n ? config.serializer.getPolyfills.bind(config.serializer)\n : () => [];\n\n const getPolyfills = (ctx: { platform: string | null }): readonly string[] => {\n if (ctx.platform === 'web') {\n return [\n // NOTE: We might need this for all platforms\n path.join(projectRoot, EXTERNAL_REQUIRE_POLYFILL),\n // TODO: runtime polyfills, i.e. Fast Refresh, error overlay, React Dev Tools...\n ];\n }\n // Generally uses `rn-get-polyfills`\n const polyfills = originalGetPolyfills(ctx);\n\n return [...polyfills, EXTERNAL_REQUIRE_NATIVE_POLYFILL];\n };\n\n return {\n ...config,\n serializer: {\n ...config.serializer,\n getPolyfills,\n },\n };\n}\n\nfunction normalizeSlashes(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n\n/**\n * Apply custom resolvers to do the following:\n * - Disable `.native.js` extensions on web.\n * - Alias `react-native` to `react-native-web` on web.\n * - Redirect `react-native-web/dist/modules/AssetRegistry/index.js` to `@react-native/assets/registry.js` on web.\n * - Add support for `tsconfig.json`/`jsconfig.json` aliases via `compilerOptions.paths`.\n */\nexport function withExtendedResolver(\n config: ConfigT,\n {\n projectRoot,\n tsconfig,\n platforms,\n isTsconfigPathsEnabled,\n }: {\n projectRoot: string;\n tsconfig: TsConfigPaths | null;\n platforms: string[];\n isTsconfigPathsEnabled?: boolean;\n }\n) {\n // Get the `transformer.assetRegistryPath`\n // this needs to be unified since you can't dynamically\n // swap out the transformer based on platform.\n const assetRegistryPath = fs.realpathSync(\n // This is the native asset registry alias for native.\n path.resolve(resolveFrom(projectRoot, 'react-native/Libraries/Image/AssetRegistry'))\n // NOTE(EvanBacon): This is the newer import but it doesn't work in the expo/expo monorepo.\n // path.resolve(resolveFrom(projectRoot, '@react-native/assets/registry.js'))\n );\n\n const isWebEnabled = platforms.includes('web');\n\n const { resolve } = importMetroResolverFromProject(projectRoot);\n\n const extraNodeModules: { [key: string]: Record<string, string> } = {};\n\n const aliases: { [key: string]: Record<string, string> } = {\n web: {\n 'react-native': 'react-native-web',\n },\n };\n\n if (isWebEnabled) {\n // Allow `react-native-web` to be optional when web is not enabled but path aliases is.\n extraNodeModules['web'] = {\n 'react-native': path.resolve(require.resolve('react-native-web/package.json'), '..'),\n };\n }\n\n const preferredMainFields: { [key: string]: string[] } = {\n // Defaults from Expo Webpack. Most packages using `react-native` don't support web\n // in the `react-native` field, so we should prefer the `browser` field.\n // https://github.com/expo/router/issues/37\n web: ['browser', 'module', 'main'],\n };\n\n let tsConfigResolve = tsconfig?.paths\n ? resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsconfig.paths ?? {},\n baseUrl: tsconfig.baseUrl,\n })\n : null;\n\n if (isTsconfigPathsEnabled && !env.CI) {\n // TODO: We should track all the files that used imports and invalidate them\n // currently the user will need to save all the files that use imports to\n // use the new aliases.\n const configWatcher = new FileNotifier(projectRoot, ['./tsconfig.json', './jsconfig.json']);\n configWatcher.startObserving(() => {\n debug('Reloading tsconfig.json');\n loadTsConfigPathsAsync(projectRoot).then((tsConfigPaths) => {\n if (tsConfigPaths?.paths && !!Object.keys(tsConfigPaths.paths).length) {\n debug('Enabling tsconfig.json paths support');\n tsConfigResolve = resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsConfigPaths.paths ?? {},\n baseUrl: tsConfigPaths.baseUrl,\n });\n } else {\n debug('Disabling tsconfig.json paths support');\n tsConfigResolve = null;\n }\n });\n });\n\n // TODO: This probably prevents the process from exiting.\n installExitHooks(() => {\n configWatcher.stopObserving();\n });\n } else {\n debug('Skipping tsconfig.json paths support');\n }\n\n return withMetroResolvers(config, projectRoot, [\n // Add a resolver to alias the web asset resolver.\n (immutableContext: ResolutionContext, moduleName: string, platform: string | null) => {\n let context = {\n ...immutableContext,\n } as Mutable<ResolutionContext> & {\n mainFields: string[];\n customResolverOptions?: Record<string, string>;\n };\n\n const environment = context.customResolverOptions?.environment;\n const isNode = environment === 'node';\n\n // TODO: We need to prevent the require.context from including API routes as these use externals.\n // Should be fine after async routes lands.\n if (isNode) {\n const moduleId = isNodeExternal(moduleName);\n if (moduleId) {\n moduleName = getNodeExternalModuleId(context.originModulePath, moduleId);\n debug(`Redirecting Node.js external \"${moduleId}\" to \"${moduleName}\"`);\n }\n }\n\n // Conditionally remap `react-native` to `react-native-web` on web in\n // a way that doesn't require Babel to resolve the alias.\n if (platform && platform in aliases && aliases[platform][moduleName]) {\n moduleName = aliases[platform][moduleName];\n }\n\n // TODO: We may be able to remove this in the future, it's doing no harm\n // by staying here.\n // Conditionally remap `react-native` to `react-native-web`\n if (platform && platform in extraNodeModules) {\n context.extraNodeModules = {\n ...extraNodeModules[platform],\n ...context.extraNodeModules,\n };\n }\n\n if (tsconfig?.baseUrl && isTsconfigPathsEnabled) {\n context = {\n ...context,\n nodeModulesPaths: [\n ...immutableContext.nodeModulesPaths,\n // add last to ensure node modules are resolved first\n tsconfig.baseUrl,\n ],\n };\n }\n\n let mainFields: string[] = context.mainFields;\n\n if (isNode) {\n // Node.js runtimes should only be importing main at the moment.\n // This is a temporary fix until we can support the package.json exports.\n mainFields = ['main'];\n } else if (env.EXPO_METRO_NO_MAIN_FIELD_OVERRIDE) {\n mainFields = context.mainFields;\n } else if (platform && platform in preferredMainFields) {\n mainFields = preferredMainFields[platform];\n }\n function doResolve(moduleName: string): Resolution | null {\n return resolve(\n {\n ...context,\n preferNativePlatform: platform !== 'web',\n resolveRequest: undefined,\n\n mainFields,\n\n // Passing `mainFields` directly won't be considered (in certain version of Metro)\n // we need to extend the `getPackageMainPath` directly to\n // use platform specific `mainFields`.\n // @ts-ignore\n getPackageMainPath(packageJsonPath) {\n // @ts-expect-error: mainFields is not on type\n const package_ = context.moduleCache.getPackage(packageJsonPath);\n return package_.getMain(mainFields);\n },\n },\n moduleName,\n platform\n );\n }\n\n function optionalResolve(moduleName: string): Resolution | null {\n try {\n return doResolve(moduleName);\n } catch (error) {\n // If the error is directly related to a resolver not being able to resolve a module, then\n // we can ignore the error and try the next resolver. Otherwise, we should throw the error.\n const isResolutionError =\n isFailedToResolveNameError(error) || isFailedToResolvePathError(error);\n if (!isResolutionError) {\n throw error;\n }\n }\n return null;\n }\n\n let result: Resolution | null = null;\n\n if (tsConfigResolve) {\n result = tsConfigResolve(\n {\n originModulePath: context.originModulePath,\n moduleName,\n },\n optionalResolve\n );\n }\n\n result ??= doResolve(moduleName);\n\n if (result) {\n // Replace the web resolver with the original one.\n // This is basically an alias for web-only.\n if (shouldAliasAssetRegistryForWeb(platform, result)) {\n // @ts-expect-error: `readonly` for some reason.\n result.filePath = assetRegistryPath;\n }\n }\n return result;\n },\n ]);\n}\n\n/** @returns `true` if the incoming resolution should be swapped on web. */\nexport function shouldAliasAssetRegistryForWeb(\n platform: string | null,\n result: Resolution\n): boolean {\n return (\n platform === 'web' &&\n result?.type === 'sourceFile' &&\n typeof result?.filePath === 'string' &&\n normalizeSlashes(result.filePath).endsWith(\n 'react-native-web/dist/modules/AssetRegistry/index.js'\n )\n );\n}\n\n/** Add support for `react-native-web` and the Web platform. */\nexport async function withMetroMultiPlatformAsync(\n projectRoot: string,\n {\n config,\n platformBundlers,\n isTsconfigPathsEnabled,\n webOutput,\n routerDirectory,\n }: {\n config: ConfigT;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n webOutput?: 'single' | 'static';\n routerDirectory: string;\n }\n) {\n // Auto pick app entry for router.\n process.env.EXPO_ROUTER_APP_ROOT = getAppRouterRelativeEntryPath(projectRoot, routerDirectory);\n\n // Required for @expo/metro-runtime to format paths in the web LogBox.\n process.env.EXPO_PUBLIC_PROJECT_ROOT = process.env.EXPO_PUBLIC_PROJECT_ROOT ?? projectRoot;\n\n if (webOutput === 'static') {\n // Enable static rendering in runtime space.\n process.env.EXPO_PUBLIC_USE_STATIC = '1';\n }\n\n // Ensure the cache is invalidated if these values change.\n // @ts-expect-error\n config.transformer._expoRouterRootDirectory = process.env.EXPO_ROUTER_APP_ROOT;\n // @ts-expect-error\n config.transformer._expoRouterWebRendering = webOutput;\n // TODO: import mode\n\n if (platformBundlers.web === 'metro') {\n await new WebSupportProjectPrerequisite(projectRoot).assertAsync();\n } else if (!isTsconfigPathsEnabled) {\n // Bail out early for performance enhancements if no special features are enabled.\n return config;\n }\n\n let tsconfig: null | TsConfigPaths = null;\n\n if (isTsconfigPathsEnabled) {\n Log.warn(\n chalk.yellow`Experimental path aliases feature is enabled. ` +\n learnMore('https://docs.expo.dev/guides/typescript/#path-aliases')\n );\n tsconfig = await loadTsConfigPathsAsync(projectRoot);\n }\n\n await setupNodeExternals(projectRoot);\n\n return withMetroMultiPlatform(projectRoot, {\n config,\n platformBundlers,\n tsconfig,\n isTsconfigPathsEnabled,\n });\n}\n\nfunction withMetroMultiPlatform(\n projectRoot: string,\n {\n config,\n platformBundlers,\n isTsconfigPathsEnabled,\n tsconfig,\n }: {\n config: ConfigT;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n tsconfig: TsConfigPaths | null;\n }\n) {\n let expoConfigPlatforms = Object.entries(platformBundlers)\n .filter(([, bundler]) => bundler === 'metro')\n .map(([platform]) => platform);\n\n if (Array.isArray(config.resolver.platforms)) {\n expoConfigPlatforms = [...new Set(expoConfigPlatforms.concat(config.resolver.platforms))];\n }\n\n // @ts-expect-error: typed as `readonly`.\n config.resolver.platforms = expoConfigPlatforms;\n\n if (expoConfigPlatforms.includes('web')) {\n config = withWebPolyfills(config, projectRoot);\n }\n\n return withExtendedResolver(config, {\n projectRoot,\n tsconfig,\n isTsconfigPathsEnabled,\n platforms: expoConfigPlatforms,\n });\n}\n"],"names":["withExtendedResolver","shouldAliasAssetRegistryForWeb","withMetroMultiPlatformAsync","debug","require","withWebPolyfills","config","projectRoot","originalGetPolyfills","serializer","getPolyfills","bind","ctx","platform","path","join","EXTERNAL_REQUIRE_POLYFILL","polyfills","EXTERNAL_REQUIRE_NATIVE_POLYFILL","normalizeSlashes","p","replace","tsconfig","platforms","isTsconfigPathsEnabled","assetRegistryPath","fs","realpathSync","resolve","resolveFrom","isWebEnabled","includes","importMetroResolverFromProject","extraNodeModules","aliases","web","preferredMainFields","tsConfigResolve","paths","resolveWithTsConfigPaths","baseUrl","env","CI","configWatcher","FileNotifier","startObserving","loadTsConfigPathsAsync","then","tsConfigPaths","Object","keys","length","installExitHooks","stopObserving","withMetroResolvers","immutableContext","moduleName","context","environment","customResolverOptions","isNode","moduleId","isNodeExternal","getNodeExternalModuleId","originModulePath","nodeModulesPaths","mainFields","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","doResolve","preferNativePlatform","resolveRequest","undefined","getPackageMainPath","packageJsonPath","package_","moduleCache","getPackage","getMain","optionalResolve","error","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","result","filePath","type","endsWith","platformBundlers","webOutput","routerDirectory","process","EXPO_ROUTER_APP_ROOT","getAppRouterRelativeEntryPath","EXPO_PUBLIC_PROJECT_ROOT","EXPO_PUBLIC_USE_STATIC","transformer","_expoRouterRootDirectory","_expoRouterWebRendering","WebSupportProjectPrerequisite","assertAsync","Log","warn","chalk","yellow","learnMore","setupNodeExternals","withMetroMultiPlatform","expoCon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AO,CAACrB,gBAAgB,CAAC,CACvDsB,MAAM,CAAC,CAAC,GAAGC,OAAO,CAAC,GAAKA,OAAO,KAAK,OAAO;IAAA,CAAC,CAC5CC,GAAG,CAAC,CAAC,CAAClG,QAAQ,CAAC,GAAKA,QAAQ;IAAA,CAAC,AAAC;IAEjC,IAAImG,KAAK,CAACC,OAAO,CAAC3G,MAAM,CAAC4G,QAAQ,CAAC3F,SAAS,CAAC,EAAE;QAC5CoF,mBAAmB,GAAG;eAAI,IAAIQ,GAAG,CAACR,mBAAmB,CAACS,MAAM,CAAC9G,MAAM,CAAC4G,QAAQ,CAAC3F,SAAS,CAAC,CAAC;SAAC,CAAC;KAC3F;IAED,yCAAyC;IACzCjB,MAAM,CAAC4G,QAAQ,CAAC3F,SAAS,GAAGoF,mBAAmB,CAAC;IAEhD,IAAIA,mBAAmB,CAAC5E,QAAQ,CAAC,KAAK,CAAC,EAAE;QACvCzB,MAAM,GAAGD,gBAAgB,CAACC,MAAM,EAAEC,WAAW,CAAC,CAAC;KAChD;IAED,OAAOP,oBAAoB,CAACM,MAAM,EAAE;QAClCC,WAAW;QACXe,QAAQ;QACRE,sBAAsB;QACtBD,SAAS,EAAEoF,mBAAmB;KAC/B,CAAC,CAAC;CACJ"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/withMetroMultiPlatform.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport { ConfigT } from 'metro-config';\nimport { Resolution, ResolutionContext } from 'metro-resolver';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { Log } from '../../../log';\nimport { FileNotifier } from '../../../utils/FileNotifier';\nimport { env } from '../../../utils/env';\nimport { installExitHooks } from '../../../utils/exit';\nimport { isInteractive } from '../../../utils/interactive';\nimport { learnMore } from '../../../utils/link';\nimport { loadTsConfigPathsAsync, TsConfigPaths } from '../../../utils/tsconfig/loadTsConfigPaths';\nimport { resolveWithTsConfigPaths } from '../../../utils/tsconfig/resolveWithTsConfigPaths';\nimport { WebSupportProjectPrerequisite } from '../../doctor/web/WebSupportProjectPrerequisite';\nimport { PlatformBundlers } from '../platformBundlers';\nimport {\n EXTERNAL_REQUIRE_NATIVE_POLYFILL,\n EXTERNAL_REQUIRE_POLYFILL,\n getNodeExternalModuleId,\n isNodeExternal,\n setupNodeExternals,\n} from './externals';\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport { importMetroResolverFromProject } from './resolveFromProject';\nimport { getAppRouterRelativeEntryPath } from './router';\nimport { withMetroResolvers } from './withMetroResolvers';\n\ntype Mutable<T> = { -readonly [K in keyof T]: T[K] };\n\nconst debug = require('debug')('expo:start:server:metro:multi-platform') as typeof console.log;\n\nfunction withWebPolyfills(config: ConfigT, projectRoot: string): ConfigT {\n const originalGetPolyfills = config.serializer.getPolyfills\n ? config.serializer.getPolyfills.bind(config.serializer)\n : () => [];\n\n const getPolyfills = (ctx: { platform: string | null }): readonly string[] => {\n if (ctx.platform === 'web') {\n return [\n // NOTE: We might need this for all platforms\n path.join(projectRoot, EXTERNAL_REQUIRE_POLYFILL),\n // TODO: runtime polyfills, i.e. Fast Refresh, error overlay, React Dev Tools...\n ];\n }\n // Generally uses `rn-get-polyfills`\n const polyfills = originalGetPolyfills(ctx);\n\n return [...polyfills, EXTERNAL_REQUIRE_NATIVE_POLYFILL];\n };\n\n return {\n ...config,\n serializer: {\n ...config.serializer,\n getPolyfills,\n },\n };\n}\n\nfunction normalizeSlashes(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n\n/**\n * Apply custom resolvers to do the following:\n * - Disable `.native.js` extensions on web.\n * - Alias `react-native` to `react-native-web` on web.\n * - Redirect `react-native-web/dist/modules/AssetRegistry/index.js` to `@react-native/assets/registry.js` on web.\n * - Add support for `tsconfig.json`/`jsconfig.json` aliases via `compilerOptions.paths`.\n */\nexport function withExtendedResolver(\n config: ConfigT,\n {\n projectRoot,\n tsconfig,\n platforms,\n isTsconfigPathsEnabled,\n }: {\n projectRoot: string;\n tsconfig: TsConfigPaths | null;\n platforms: string[];\n isTsconfigPathsEnabled?: boolean;\n }\n) {\n // Get the `transformer.assetRegistryPath`\n // this needs to be unified since you can't dynamically\n // swap out the transformer based on platform.\n const assetRegistryPath = fs.realpathSync(\n // This is the native asset registry alias for native.\n path.resolve(resolveFrom(projectRoot, 'react-native/Libraries/Image/AssetRegistry'))\n // NOTE(EvanBacon): This is the newer import but it doesn't work in the expo/expo monorepo.\n // path.resolve(resolveFrom(projectRoot, '@react-native/assets/registry.js'))\n );\n\n const isWebEnabled = platforms.includes('web');\n\n const { resolve } = importMetroResolverFromProject(projectRoot);\n\n const extraNodeModules: { [key: string]: Record<string, string> } = {};\n\n const aliases: { [key: string]: Record<string, string> } = {\n web: {\n 'react-native': 'react-native-web',\n },\n };\n\n if (isWebEnabled) {\n // Allow `react-native-web` to be optional when web is not enabled but path aliases is.\n extraNodeModules['web'] = {\n 'react-native': path.resolve(require.resolve('react-native-web/package.json'), '..'),\n };\n }\n\n const preferredMainFields: { [key: string]: string[] } = {\n // Defaults from Expo Webpack. Most packages using `react-native` don't support web\n // in the `react-native` field, so we should prefer the `browser` field.\n // https://github.com/expo/router/issues/37\n web: ['browser', 'module', 'main'],\n };\n\n let tsConfigResolve = tsconfig?.paths\n ? resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsconfig.paths ?? {},\n baseUrl: tsconfig.baseUrl,\n })\n : null;\n\n if (isTsconfigPathsEnabled && isInteractive()) {\n // TODO: We should track all the files that used imports and invalidate them\n // currently the user will need to save all the files that use imports to\n // use the new aliases.\n const configWatcher = new FileNotifier(projectRoot, ['./tsconfig.json', './jsconfig.json']);\n configWatcher.startObserving(() => {\n debug('Reloading tsconfig.json');\n loadTsConfigPathsAsync(projectRoot).then((tsConfigPaths) => {\n if (tsConfigPaths?.paths && !!Object.keys(tsConfigPaths.paths).length) {\n debug('Enabling tsconfig.json paths support');\n tsConfigResolve = resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsConfigPaths.paths ?? {},\n baseUrl: tsConfigPaths.baseUrl,\n });\n } else {\n debug('Disabling tsconfig.json paths support');\n tsConfigResolve = null;\n }\n });\n });\n\n // TODO: This probably prevents the process from exiting.\n installExitHooks(() => {\n configWatcher.stopObserving();\n });\n } else {\n debug('Skipping tsconfig.json paths support');\n }\n\n return withMetroResolvers(config, projectRoot, [\n // Add a resolver to alias the web asset resolver.\n (immutableContext: ResolutionContext, moduleName: string, platform: string | null) => {\n let context = {\n ...immutableContext,\n } as Mutable<ResolutionContext> & {\n mainFields: string[];\n customResolverOptions?: Record<string, string>;\n };\n\n const environment = context.customResolverOptions?.environment;\n const isNode = environment === 'node';\n\n // TODO: We need to prevent the require.context from including API routes as these use externals.\n // Should be fine after async routes lands.\n if (isNode) {\n const moduleId = isNodeExternal(moduleName);\n if (moduleId) {\n moduleName = getNodeExternalModuleId(context.originModulePath, moduleId);\n debug(`Redirecting Node.js external \"${moduleId}\" to \"${moduleName}\"`);\n }\n }\n\n // Conditionally remap `react-native` to `react-native-web` on web in\n // a way that doesn't require Babel to resolve the alias.\n if (platform && platform in aliases && aliases[platform][moduleName]) {\n moduleName = aliases[platform][moduleName];\n }\n\n // TODO: We may be able to remove this in the future, it's doing no harm\n // by staying here.\n // Conditionally remap `react-native` to `react-native-web`\n if (platform && platform in extraNodeModules) {\n context.extraNodeModules = {\n ...extraNodeModules[platform],\n ...context.extraNodeModules,\n };\n }\n\n if (tsconfig?.baseUrl && isTsconfigPathsEnabled) {\n context = {\n ...context,\n nodeModulesPaths: [\n ...immutableContext.nodeModulesPaths,\n // add last to ensure node modules are resolved first\n tsconfig.baseUrl,\n ],\n };\n }\n\n let mainFields: string[] = context.mainFields;\n\n if (isNode) {\n // Node.js runtimes should only be importing main at the moment.\n // This is a temporary fix until we can support the package.json exports.\n mainFields = ['main'];\n } else if (env.EXPO_METRO_NO_MAIN_FIELD_OVERRIDE) {\n mainFields = context.mainFields;\n } else if (platform && platform in preferredMainFields) {\n mainFields = preferredMainFields[platform];\n }\n function doResolve(moduleName: string): Resolution | null {\n return resolve(\n {\n ...context,\n preferNativePlatform: platform !== 'web',\n resolveRequest: undefined,\n\n mainFields,\n\n // Passing `mainFields` directly won't be considered (in certain version of Metro)\n // we need to extend the `getPackageMainPath` directly to\n // use platform specific `mainFields`.\n // @ts-ignore\n getPackageMainPath(packageJsonPath) {\n // @ts-expect-error: mainFields is not on type\n const package_ = context.moduleCache.getPackage(packageJsonPath);\n return package_.getMain(mainFields);\n },\n },\n moduleName,\n platform\n );\n }\n\n function optionalResolve(moduleName: string): Resolution | null {\n try {\n return doResolve(moduleName);\n } catch (error) {\n // If the error is directly related to a resolver not being able to resolve a module, then\n // we can ignore the error and try the next resolver. Otherwise, we should throw the error.\n const isResolutionError =\n isFailedToResolveNameError(error) || isFailedToResolvePathError(error);\n if (!isResolutionError) {\n throw error;\n }\n }\n return null;\n }\n\n let result: Resolution | null = null;\n\n if (tsConfigResolve) {\n result = tsConfigResolve(\n {\n originModulePath: context.originModulePath,\n moduleName,\n },\n optionalResolve\n );\n }\n\n result ??= doResolve(moduleName);\n\n if (result) {\n // Replace the web resolver with the original one.\n // This is basically an alias for web-only.\n if (shouldAliasAssetRegistryForWeb(platform, result)) {\n // @ts-expect-error: `readonly` for some reason.\n result.filePath = assetRegistryPath;\n }\n }\n return result;\n },\n ]);\n}\n\n/** @returns `true` if the incoming resolution should be swapped on web. */\nexport function shouldAliasAssetRegistryForWeb(\n platform: string | null,\n result: Resolution\n): boolean {\n return (\n platform === 'web' &&\n result?.type === 'sourceFile' &&\n typeof result?.filePath === 'string' &&\n normalizeSlashes(result.filePath).endsWith(\n 'react-native-web/dist/modules/AssetRegistry/index.js'\n )\n );\n}\n\n/** Add support for `react-native-web` and the Web platform. */\nexport async function withMetroMultiPlatformAsync(\n projectRoot: string,\n {\n config,\n platformBundlers,\n isTsconfigPathsEnabled,\n webOutput,\n routerDirectory,\n }: {\n config: ConfigT;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n webOutput?: 'single' | 'static';\n routerDirectory: string;\n }\n) {\n // Auto pick app entry for router.\n process.env.EXPO_ROUTER_APP_ROOT = getAppRouterRelativeEntryPath(projectRoot, routerDirectory);\n\n // Required for @expo/metro-runtime to format paths in the web LogBox.\n process.env.EXPO_PUBLIC_PROJECT_ROOT = process.env.EXPO_PUBLIC_PROJECT_ROOT ?? projectRoot;\n\n if (webOutput === 'static') {\n // Enable static rendering in runtime space.\n process.env.EXPO_PUBLIC_USE_STATIC = '1';\n }\n\n // Ensure the cache is invalidated if these values change.\n // @ts-expect-error\n config.transformer._expoRouterRootDirectory = process.env.EXPO_ROUTER_APP_ROOT;\n // @ts-expect-error\n config.transformer._expoRouterWebRendering = webOutput;\n // TODO: import mode\n\n if (platformBundlers.web === 'metro') {\n await new WebSupportProjectPrerequisite(projectRoot).assertAsync();\n } else if (!isTsconfigPathsEnabled) {\n // Bail out early for performance enhancements if no special features are enabled.\n return config;\n }\n\n let tsconfig: null | TsConfigPaths = null;\n\n if (isTsconfigPathsEnabled) {\n Log.warn(\n chalk.yellow`Experimental path aliases feature is enabled. ` +\n learnMore('https://docs.expo.dev/guides/typescript/#path-aliases')\n );\n tsconfig = await loadTsConfigPathsAsync(projectRoot);\n }\n\n await setupNodeExternals(projectRoot);\n\n return withMetroMultiPlatform(projectRoot, {\n config,\n platformBundlers,\n tsconfig,\n isTsconfigPathsEnabled,\n });\n}\n\nfunction withMetroMultiPlatform(\n projectRoot: string,\n {\n config,\n platformBundlers,\n isTsconfigPathsEnabled,\n tsconfig,\n }: {\n config: ConfigT;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n tsconfig: TsConfigPaths | null;\n }\n) {\n let expoConfigPlatforms = Object.entries(platformBundlers)\n .filter(([, bundler]) => bundler === 'metro')\n .map(([platform]) => platform);\n\n if (Array.isArray(config.resolver.platforms)) {\n expoConfigPlatforms = [...new Set(expoConfigPlatforms.concat(config.resolver.platforms))];\n }\n\n // @ts-expect-error: typed as `readonly`.\n config.resolver.platforms = expoConfigPlatforms;\n\n if (expoConfigPlatforms.includes('web')) {\n config = withWebPolyfills(config, projectRoot);\n }\n\n return withExtendedResolver(config, {\n projectRoot,\n tsconfig,\n isTsconfigPathsEnabled,\n platforms: expoConfigPlatforms,\n });\n}\n"],"names":["withExtendedResolver","shouldAliasAssetRegistryForWeb","withMetroMultiPlatformAsync","debug","require","withWebPolyfills","config","projectRoot","originalGetPolyfills","serializer","getPolyfills","bind","ctx","platform","path","join","EXTERNAL_REQUIRE_POLYFILL","polyfills","EXTERNAL_REQUIRE_NATIVE_POLYFILL","normalizeSlashes","p","replace","tsconfig","platforms","isTsconfigPathsEnabled","assetRegistryPath","fs","realpathSync","resolve","resolveFrom","isWebEnabled","includes","importMetroResolverFromProject","extraNodeModules","aliases","web","preferredMainFields","tsConfigResolve","paths","resolveWithTsConfigPaths","baseUrl","isInteractive","configWatcher","FileNotifier","startObserving","loadTsConfigPathsAsync","then","tsConfigPaths","Object","keys","length","installExitHooks","stopObserving","withMetroResolvers","immutableContext","moduleName","context","environment","customResolverOptions","isNode","moduleId","isNodeExternal","getNodeExternalModuleId","originModulePath","nodeModulesPaths","mainFields","env","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","doResolve","preferNativePlatform","resolveRequest","undefined","getPackageMainPath","packageJsonPath","package_","moduleCache","getPackage","getMain","optionalResolve","error","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","result","filePath","type","endsWith","platformBundlers","webOutput","routerDirectory","process","EXPO_ROUTER_APP_ROOT","getAppRouterRelativeEntryPath","EXPO_PUBLIC_PROJECT_ROOT","EXPO_PUBLIC_USE_STATIC","transformer","_expoRouterRootDirectory","_expoRouterWebRendering","WebSupportProjectPrerequisite","assertAsync","Log","warn","chalk","yellow","learnMore","setupNodeExternals","withMetroMultiPlatform","expoConfigPlatforms","entries","filter","bundler","map","Array","isArray","resolver","Set","concat"],"mappings":"AAMA;;;;QAwEgBA,oBAAoB,GAApBA,oBAAoB;QAsNpBC,8BAA8B,GAA9BA,8BAA8B;QAexBC,2BAA2B,GAA3BA,2BAA2B;AA7S/B,IAAA,MAAO,kCAAP,OAAO,EAAA;AACV,IAAA,GAAI,kCAAJ,IAAI,EAAA;AAGF,IAAA,KAAM,kCAAN,MAAM,EAAA;AACC,IAAA,YAAc,kCAAd,cAAc,EAAA;AAElB,IAAA,IAAc,WAAd,cAAc,CAAA;AACL,IAAA,aAA6B,WAA7B,6BAA6B,CAAA;AACtC,IAAA,IAAoB,WAApB,oBAAoB,CAAA;AACP,IAAA,KAAqB,WAArB,qBAAqB,CAAA;AACxB,IAAA,YAA4B,WAA5B,4BAA4B,CAAA;AAChC,IAAA,KAAqB,WAArB,qBAAqB,CAAA;AACO,IAAA,kBAA2C,WAA3C,2CAA2C,CAAA;AACxD,IAAA,yBAAkD,WAAlD,kDAAkD,CAAA;AAC7C,IAAA,8BAAgD,WAAhD,gDAAgD,CAAA;AAQvF,IAAA,UAAa,WAAb,aAAa,CAAA;AACmD,IAAA,YAAe,WAAf,eAAe,CAAA;AACvC,IAAA,mBAAsB,WAAtB,sBAAsB,CAAA;AACvB,IAAA,OAAU,WAAV,UAAU,CAAA;AACrB,IAAA,mBAAsB,WAAtB,sBAAsB,CAAA;;;;;;AAIzD,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,wCAAwC,CAAC,AAAsB,AAAC;AAE/F,SAASC,gBAAgB,CAACC,MAAe,EAAEC,WAAmB,EAAW;IACvE,MAAMC,oBAAoB,GAAGF,MAAM,CAACG,UAAU,CAACC,YAAY,GACvDJ,MAAM,CAACG,UAAU,CAACC,YAAY,CAACC,IAAI,CAACL,MAAM,CAACG,UAAU,CAAC,GACtD,IAAM,EAAE;IAAC;IAEb,MAAMC,YAAY,GAAG,CAACE,GAAg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QAAQ,CAAA,EAMT,EACD;IACA,IAAIqF,mBAAmB,GAAG3D,MAAM,CAAC4D,OAAO,CAACrB,gBAAgB,CAAC,CACvDsB,MAAM,CAAC,CAAC,GAAGC,OAAO,CAAC,GAAKA,OAAO,KAAK,OAAO;IAAA,CAAC,CAC5CC,GAAG,CAAC,CAAC,CAAClG,QAAQ,CAAC,GAAKA,QAAQ;IAAA,CAAC,AAAC;IAEjC,IAAImG,KAAK,CAACC,OAAO,CAAC3G,MAAM,CAAC4G,QAAQ,CAAC3F,SAAS,CAAC,EAAE;QAC5CoF,mBAAmB,GAAG;eAAI,IAAIQ,GAAG,CAACR,mBAAmB,CAACS,MAAM,CAAC9G,MAAM,CAAC4G,QAAQ,CAAC3F,SAAS,CAAC,CAAC;SAAC,CAAC;KAC3F;IAED,yCAAyC;IACzCjB,MAAM,CAAC4G,QAAQ,CAAC3F,SAAS,GAAGoF,mBAAmB,CAAC;IAEhD,IAAIA,mBAAmB,CAAC5E,QAAQ,CAAC,KAAK,CAAC,EAAE;QACvCzB,MAAM,GAAGD,gBAAgB,CAACC,MAAM,EAAEC,WAAW,CAAC,CAAC;KAChD;IAED,OAAOP,oBAAoB,CAACM,MAAM,EAAE;QAClCC,WAAW;QACXe,QAAQ;QACRE,sBAAsB;QACtBD,SAAS,EAAEoF,mBAAmB;KAC/B,CAAC,CAAC;CACJ"}
|
|
@@ -138,7 +138,7 @@ async function createHostInfoAsync() {
|
|
|
138
138
|
host: await _userSettings.default.getAnonymousIdentifierAsync(),
|
|
139
139
|
server: "expo",
|
|
140
140
|
// Defined in the build step
|
|
141
|
-
serverVersion: "0.10.
|
|
141
|
+
serverVersion: "0.10.9",
|
|
142
142
|
serverDriver: _manifestMiddleware.DEVELOPER_TOOL,
|
|
143
143
|
serverOS: _os.default.platform(),
|
|
144
144
|
serverOSVersion: _os.default.release()
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
var _build = _interopRequireWildcard(require("expo-router/build"));
|
|
6
|
+
Object.keys(_build).forEach(function(key) {
|
|
7
|
+
if (key === "default" || key === "__esModule") return;
|
|
8
|
+
if (key in exports && exports[key] === _build[key]) return;
|
|
9
|
+
Object.defineProperty(exports, key, {
|
|
10
|
+
enumerable: true,
|
|
11
|
+
get: function() {
|
|
12
|
+
return _build[key];
|
|
13
|
+
}
|
|
14
|
+
});
|
|
15
|
+
});
|
|
16
|
+
function _interopRequireWildcard(obj) {
|
|
17
|
+
if (obj && obj.__esModule) {
|
|
18
|
+
return obj;
|
|
19
|
+
} else {
|
|
20
|
+
var newObj = {};
|
|
21
|
+
if (obj != null) {
|
|
22
|
+
for(var key in obj){
|
|
23
|
+
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
|
24
|
+
var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {};
|
|
25
|
+
if (desc.get || desc.set) {
|
|
26
|
+
Object.defineProperty(newObj, key, desc);
|
|
27
|
+
} else {
|
|
28
|
+
newObj[key] = obj[key];
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
newObj.default = obj;
|
|
34
|
+
return newObj;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
//# sourceMappingURL=basic.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../src/start/server/type-generation/__typetests__/fixtures/basic.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/ban-types */\n\nimport type { LinkProps as OriginalLinkProps } from 'expo-router/build/link/Link';\nexport * from 'expo-router/build';\n\n// prettier-ignore\ntype StaticRoutes = `/apple` | `/banana`;\n// prettier-ignore\ntype DynamicRoutes<T extends string> = `/colors/${SingleRoutePart<T>}` | `/animals/${CatchAllRoutePart<T>}` | `/mix/${SingleRoutePart<T>}/${SingleRoutePart<T>}/${CatchAllRoutePart<T>}`;\n// prettier-ignore\ntype DynamicRouteTemplate = `/colors/[color]` | `/animals/[...animal]` | `/mix/[fruit]/[color]/[...animals]`;\n\ntype RelativePathString = `./${string}` | `../${string}` | '..';\ntype AbsoluteRoute = DynamicRouteTemplate | StaticRoutes;\ntype ExternalPathString = `http${string}`;\ntype ExpoRouterRoutes = DynamicRouteTemplate | StaticRoutes | RelativePathString;\ntype AllRoutes = ExpoRouterRoutes | ExternalPathString;\n\n/****************\n * Route Utils *\n ****************/\n\ntype SearchOrHash = `?${string}` | `#${string}`;\n\n/**\n * Return only the RoutePart of a string. If the string has multiple parts return never\n *\n * string | type\n * ---------|------\n * 123 | 123\n * /123/abc | never\n * 123?abc | never\n * ./123 | never\n * /123 | never\n * 123/../ | never\n */\ntype SingleRoutePart<S extends string> = S extends `${string}/${string}`\n ? never\n : S extends `${string}${SearchOrHash}`\n ? never\n : S extends ''\n ? never\n : S;\n\n/**\n * Return only the CatchAll router part. If the string has search parameters or a hash return never\n */\ntype CatchAllRoutePart<S extends string> = S extends `${string}${SearchOrHash}`\n ? never\n : S extends ''\n ? never\n : S;\n\n// type OptionalCatchAllRoutePart<S extends string> = S extends `${string}${SearchOrHash}` ? never : S\n\n/**\n * Return the name of a route parameter\n * '[test]' -> 'test'\n * 'test' -> never\n * '[...test]' -> '...test'\n */\ntype IsParameter<Part> = Part extends `[${infer ParamName}]` ? ParamName : never;\n\n/**\n * Return a union of all parameter names. If there are no names return never\n *\n * /[test] -> 'test'\n * /[abc]/[...def] -> 'abc'|'...def'\n */\ntype ParameterNames<Path> = Path extends `${infer PartA}/${infer PartB}`\n ? IsParameter<PartA> | ParameterNames<PartB>\n : IsParameter<Path>;\n\n/**\n * Returns all segements of a route.\n *\n * /(group)/123/abc/[id]/[...rest] -> ['(group)', '123', 'abc', '[id]', '[...rest]'\n */\ntype RouteSegments<Path> = Path extends `${infer PartA}/${infer PartB}`\n ? PartA extends '' | '.'\n ? [...RouteSegments<PartB>]\n : [PartA, ...RouteSegments<PartB>]\n : Path extends ''\n ? []\n : [Path];\n\n/**\n * Returns a Record of the routes parameters as strings and CatchAll parameters as string[]\n *\n * /[id]/[...rest] -> { id: string, rest: string[] }\n * /no-params -> {}\n */\ntype RouteParams<Path> = {\n [Key in ParameterNames<Path> as Key extends `...${infer Name}`\n ? Name\n : Key]: Key extends `...${string}` ? string[] : string;\n};\n\n/**\n * Returns the search parameters for a route\n */\nexport type SearchParams<T extends AllRoutes> = T extends DynamicRouteTemplate\n ? RouteParams<T>\n : T extends StaticRoutes\n ? never\n : Record<string, string>;\n\n/**\n * Route is mostly used as part of Href to ensure that a valid route is provided\n *\n * Given a dynamic route, this will return never. This is helpful for conditional logic\n *\n * /test -> /test, /test2, etc\n * /test/[abc] -> never\n * /test/resolve -> /test, /test2, etc\n *\n * Note that if we provide a value for [abc] then the route is allowed\n *\n * This is named Route to prevent confusion, as users they will often see it in tooltips\n */\nexport type Route<T> = T extends DynamicRouteTemplate\n ? never\n :\n | StaticRoutes\n | RelativePathString\n | ExternalPathString\n | (T extends DynamicRoutes<infer _> ? T : never);\n\n/*********\n * Href *\n *********/\n\nexport type Href<T extends string> = Route<T> | HrefObject<T>;\n\nexport type HrefObject<T = AllRoutes> = T extends DynamicRouteTemplate\n ? { pathname: T; params: RouteParams<T> }\n : T extends Route<T>\n ? { pathname: Route<T>; params?: never }\n : never;\n\n/***********************\n * Expo Router Exports *\n ***********************/\n\nexport type Router = {\n /** Navigate to the provided href. */\n push: <T extends string>(href: Href<T>) => void;\n /** Navigate to route without appending to the history. */\n replace: <T extends string>(href: Href<T>) => void;\n /** Go back in the history. */\n back: () => void;\n /** Update the current route query params. */\n setParams: <T extends string = ''>(\n params?: T extends '' ? Record<string, string> : RouteParams<T>\n ) => void;\n};\n\n/************\n * <Link /> *\n ************/\nexport interface LinkProps<T extends string> extends OriginalLinkProps {\n href: T extends DynamicRouteTemplate ? HrefObject<T> : Href<T>;\n}\n\nexport interface LinkComponent {\n <T extends string>(props: React.PropsWithChildren<LinkProps<T>>): JSX.Element;\n /** Helper method to resolve an Href object into a string. */\n resolveHref: <T extends string>(href: Href<T>) => string;\n}\n\nexport declare const Link: LinkComponent;\n\n/************\n * Hooks *\n ************/\nexport declare function useRouter(): Router;\nexport declare function useLocalSearchParams<\n T extends DynamicRouteTemplate | StaticRoutes | RelativePathString\n>(): SearchParams<T>;\nexport declare function useSearchParams<\n T extends AllRoutes | SearchParams<DynamicRouteTemplate>\n>(): T extends AllRoutes ? SearchParams<T> : T;\n\nexport declare function useGlobalSearchParams<\n T extends AllRoutes | SearchParams<DynamicRouteTemplate>\n>(): T extends AllRoutes ? SearchParams<T> : T;\n\nexport declare function useSegments<\n T extends AbsoluteRoute | RouteSegments<AbsoluteRoute> | RelativePathString\n>(): T extends AbsoluteRoute ? RouteSegments<T> : T extends string ? string[] : T;\n"],"names":[],"mappings":"AAIA;;;;6CACc,mBAAmB;AAAjC,YAAA,MAAkC;;2CAAlC,MAAkC;;;;mBAAlC,MAAkC;;;EAAA"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
exports.default = _default;
|
|
6
|
+
var _promises = require("fs/promises");
|
|
7
|
+
var _path = require("path");
|
|
8
|
+
var _routes = require("../routes");
|
|
9
|
+
const fixtures = {
|
|
10
|
+
basic: {
|
|
11
|
+
staticRoutes: [
|
|
12
|
+
"/apple",
|
|
13
|
+
"/banana"
|
|
14
|
+
],
|
|
15
|
+
dynamicRoutes: [
|
|
16
|
+
"/colors/${SingleRoutePart<T>}",
|
|
17
|
+
"/animals/${CatchAllRoutePart<T>}",
|
|
18
|
+
"/mix/${SingleRoutePart<T>}/${SingleRoutePart<T>}/${CatchAllRoutePart<T>}",
|
|
19
|
+
],
|
|
20
|
+
dynamicRouteTemplates: [
|
|
21
|
+
"/colors/[color]",
|
|
22
|
+
"/animals/[...animal]",
|
|
23
|
+
"/mix/[fruit]/[color]/[...animals]",
|
|
24
|
+
]
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
async function _default() {
|
|
28
|
+
await Promise.all(Object.entries(fixtures).map(async ([key, value])=>{
|
|
29
|
+
const template = (0, _routes).getTemplateString(new Set(value.staticRoutes), new Set(value.dynamicRoutes), new Set(value.dynamicRouteTemplates))// The Template produces a global module .d.ts declaration
|
|
30
|
+
// These replacements turn it into a local module
|
|
31
|
+
.replaceAll(/^ /gm, "").replace(/declare module "expo-router" {/, "").replaceAll(/export function/g, "export declare function").replaceAll(/export const/g, "export declare const")// Remove the last `}`
|
|
32
|
+
.slice(0, -2);
|
|
33
|
+
return (0, _promises).writeFile((0, _path).join(__dirname, "./fixtures/", key + ".ts"), template);
|
|
34
|
+
}));
|
|
35
|
+
console.log("done");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
//# sourceMappingURL=generateFixtures.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../src/start/server/type-generation/__typetests__/generateFixtures.ts"],"sourcesContent":["import { writeFile } from 'fs/promises';\nimport { join } from 'path';\n\nimport { getTemplateString } from '../routes';\n\ntype Fixture = {\n staticRoutes: string[];\n dynamicRoutes: string[];\n dynamicRouteTemplates: string[];\n};\n\nconst fixtures: Record<string, Fixture> = {\n basic: {\n staticRoutes: ['/apple', '/banana'],\n dynamicRoutes: [\n '/colors/${SingleRoutePart<T>}',\n '/animals/${CatchAllRoutePart<T>}',\n '/mix/${SingleRoutePart<T>}/${SingleRoutePart<T>}/${CatchAllRoutePart<T>}',\n ],\n dynamicRouteTemplates: [\n '/colors/[color]',\n '/animals/[...animal]',\n '/mix/[fruit]/[color]/[...animals]',\n ],\n },\n};\n\nexport default async function () {\n await Promise.all(\n Object.entries(fixtures).map(async ([key, value]) => {\n const template = getTemplateString(\n new Set(value.staticRoutes),\n new Set(value.dynamicRoutes),\n new Set(value.dynamicRouteTemplates)\n )\n // The Template produces a global module .d.ts declaration\n // These replacements turn it into a local module\n .replaceAll(/^ /gm, '')\n .replace(/declare module \"expo-router\" {/, '')\n .replaceAll(/export function/g, 'export declare function')\n .replaceAll(/export const/g, 'export declare const')\n // Remove the last `}`\n .slice(0, -2);\n\n return writeFile(join(__dirname, './fixtures/', key + '.ts'), template);\n })\n );\n\n console.log('done');\n}\n"],"names":["fixtures","basic","staticRoutes","dynamicRoutes","dynamicRouteTemplates","Promise","all","Object","entries","map","key","value","template","getTemplateString","Set","replaceAll","replace","slice","writeFile","join","__dirname","console","log"],"mappings":"AAAA;;;;;AAA0B,IAAA,SAAa,WAAb,aAAa,CAAA;AAClB,IAAA,KAAM,WAAN,MAAM,CAAA;AAEO,IAAA,OAAW,WAAX,WAAW,CAAA;AAQ7C,MAAMA,QAAQ,GAA4B;IACxCC,KAAK,EAAE;QACLC,YAAY,EAAE;YAAC,QAAQ;YAAE,SAAS;SAAC;QACnCC,aAAa,EAAE;YACb,+BAA+B;YAC/B,kCAAkC;YAClC,0EAA0E;SAC3E;QACDC,qBAAqB,EAAE;YACrB,iBAAiB;YACjB,sBAAsB;YACtB,mCAAmC;SACpC;KACF;CACF,AAAC;AAEa,0BAAkB;IAC/B,MAAMC,OAAO,CAACC,GAAG,CACfC,MAAM,CAACC,OAAO,CAACR,QAAQ,CAAC,CAACS,GAAG,CAAC,OAAO,CAACC,GAAG,EAAEC,KAAK,CAAC,GAAK;QACnD,MAAMC,QAAQ,GAAGC,CAAAA,GAAAA,OAAiB,AAIjC,CAAA,kBAJiC,CAChC,IAAIC,GAAG,CAACH,KAAK,CAACT,YAAY,CAAC,EAC3B,IAAIY,GAAG,CAACH,KAAK,CAACR,aAAa,CAAC,EAC5B,IAAIW,GAAG,CAACH,KAAK,CAACP,qBAAqB,CAAC,CACrC,AACC,0DAA0D;QAC1D,iDAAiD;SAChDW,UAAU,UAA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