@expo/cli 56.1.16 → 56.1.18

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.
Files changed (37) hide show
  1. package/build/bin/cli +1 -1
  2. package/build/src/events/index.js +1 -1
  3. package/build/src/export/createMetadataJson.js.map +1 -1
  4. package/build/src/export/embed/exportEmbedAsync.js +6 -3
  5. package/build/src/export/embed/exportEmbedAsync.js.map +1 -1
  6. package/build/src/export/embed/resolveOptions.js +2 -1
  7. package/build/src/export/embed/resolveOptions.js.map +1 -1
  8. package/build/src/export/exportApp.js +1 -1
  9. package/build/src/export/exportApp.js.map +1 -1
  10. package/build/src/export/exportHermes.js +9 -1
  11. package/build/src/export/exportHermes.js.map +1 -1
  12. package/build/src/export/resolveOptions.js +9 -10
  13. package/build/src/export/resolveOptions.js.map +1 -1
  14. package/build/src/export/saveAssets.js.map +1 -1
  15. package/build/src/start/server/metro/createExpoAutolinkingResolver.js +21 -8
  16. package/build/src/start/server/metro/createExpoAutolinkingResolver.js.map +1 -1
  17. package/build/src/start/server/metro/instantiateMetro.js +5 -2
  18. package/build/src/start/server/metro/instantiateMetro.js.map +1 -1
  19. package/build/src/start/server/metro/withMetroMultiPlatform.js +88 -11
  20. package/build/src/start/server/metro/withMetroMultiPlatform.js.map +1 -1
  21. package/build/src/start/server/middleware/ExpoGoManifestHandlerMiddleware.js +3 -1
  22. package/build/src/start/server/middleware/ExpoGoManifestHandlerMiddleware.js.map +1 -1
  23. package/build/src/start/server/middleware/InterstitialPageMiddleware.js +3 -1
  24. package/build/src/start/server/middleware/InterstitialPageMiddleware.js.map +1 -1
  25. package/build/src/start/server/middleware/resolvePlatform.js +4 -2
  26. package/build/src/start/server/middleware/resolvePlatform.js.map +1 -1
  27. package/build/src/start/server/platformBundlers.js +3 -1
  28. package/build/src/start/server/platformBundlers.js.map +1 -1
  29. package/build/src/utils/findUp.js +17 -19
  30. package/build/src/utils/findUp.js.map +1 -1
  31. package/build/src/utils/telemetry/Telemetry.js +5 -0
  32. package/build/src/utils/telemetry/Telemetry.js.map +1 -1
  33. package/build/src/utils/telemetry/clients/FetchClient.js +1 -1
  34. package/build/src/utils/telemetry/utils/agent.js +42 -0
  35. package/build/src/utils/telemetry/utils/agent.js.map +1 -0
  36. package/build/src/utils/telemetry/utils/context.js +1 -1
  37. package/package.json +19 -18
@@ -25,31 +25,29 @@ function _config() {
25
25
  }
26
26
  const _platformBundlers = require("../start/server/platformBundlers");
27
27
  const _errors = require("../utils/errors");
28
- function resolvePlatformOption(exp, platformBundlers, platform = [
28
+ function resolvePlatformOption(configPlatforms, platformBundlers, platform = [
29
29
  'all'
30
30
  ]) {
31
- const platformsAvailable = Object.fromEntries(Object.entries(platformBundlers).filter(([platform, bundler])=>{
32
- var _exp_platforms;
33
- return bundler === 'metro' && ((_exp_platforms = exp.platforms) == null ? void 0 : _exp_platforms.includes(platform));
34
- }));
31
+ const platformsAvailable = Object.fromEntries(Object.entries(platformBundlers).filter(([platform, bundler])=>bundler === 'metro' && configPlatforms.includes(platform)));
35
32
  if (!Object.keys(platformsAvailable).length) {
36
33
  throw new _errors.CommandError(`No platforms are configured to use the Metro bundler in the project Expo config.`);
37
34
  }
38
35
  const assertPlatformBundler = (platform)=>{
39
36
  if (!platformsAvailable[platform]) {
40
- var _exp_platforms, _exp_platforms1;
41
- if (!((_exp_platforms = exp.platforms) == null ? void 0 : _exp_platforms.includes(platform)) && platform === 'web') {
37
+ if (!configPlatforms.includes(platform) && platform === 'web') {
42
38
  // Pass through so the more robust error message is shown.
43
39
  return platform;
44
40
  }
45
- throw new _errors.CommandError('BAD_ARGS', `Platform "${platform}" is not configured to use the Metro bundler in the project Expo config, or is missing from the supported platforms in the platforms array: [${(_exp_platforms1 = exp.platforms) == null ? void 0 : _exp_platforms1.join(', ')}].`);
41
+ throw new _errors.CommandError('BAD_ARGS', `Platform "${platform}" is not configured to use the Metro bundler in the project Expo config, or is missing from the supported platforms in the platforms array: [${configPlatforms.join(', ')}].`);
46
42
  }
47
43
  return platform;
48
44
  };
49
45
  const knownPlatforms = [
50
46
  'android',
51
47
  'ios',
52
- 'web'
48
+ 'web',
49
+ 'tvos',
50
+ 'macos'
53
51
  ];
54
52
  const assertPlatformIsKnown = (platform)=>{
55
53
  if (!knownPlatforms.includes(platform)) {
@@ -68,7 +66,8 @@ async function resolveOptionsAsync(projectRoot, args) {
68
66
  skipSDKVersionRequirement: true
69
67
  });
70
68
  const platformBundlers = (0, _platformBundlers.getPlatformBundlers)(projectRoot, exp);
71
- const platforms = resolvePlatformOption(exp, platformBundlers, args['--platform']);
69
+ const platformsFromConfig = (0, _config().getPlatformsFromConfig)(projectRoot, exp);
70
+ const platforms = resolvePlatformOption(platformsFromConfig, platformBundlers, args['--platform']);
72
71
  // --source-maps can be true, "external", or "inline"
73
72
  const sourceMapsArg = args['--source-maps'];
74
73
  const sourceMaps = !!sourceMapsArg;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/export/resolveOptions.ts"],"sourcesContent":["import type { ExpoConfig, Platform } from '@expo/config';\nimport { getConfig } from '@expo/config';\n\nimport type { PlatformBundlers } from '../start/server/platformBundlers';\nimport { getPlatformBundlers } from '../start/server/platformBundlers';\nimport { CommandError } from '../utils/errors';\n\nexport type Options = {\n outputDir: string;\n platforms: Platform[];\n maxWorkers?: number;\n dev: boolean;\n clear: boolean;\n minify: boolean;\n bytecode: boolean;\n dumpAssetmap: boolean;\n sourceMaps: boolean;\n inlineSourceMaps: boolean;\n skipSSG: boolean;\n hostedNative: boolean;\n};\n\n/** Returns an array of platforms based on the input platform identifier and runtime constraints. */\nexport function resolvePlatformOption(\n exp: ExpoConfig,\n platformBundlers: PlatformBundlers,\n platform: string[] = ['all']\n): Platform[] {\n const platformsAvailable: Partial<PlatformBundlers> = Object.fromEntries(\n Object.entries(platformBundlers).filter(\n ([platform, bundler]) => bundler === 'metro' && exp.platforms?.includes(platform as Platform)\n )\n );\n\n if (!Object.keys(platformsAvailable).length) {\n throw new CommandError(\n `No platforms are configured to use the Metro bundler in the project Expo config.`\n );\n }\n\n const assertPlatformBundler = (platform: Platform): Platform => {\n if (!platformsAvailable[platform]) {\n if (!exp.platforms?.includes(platform) && platform === 'web') {\n // Pass through so the more robust error message is shown.\n return platform;\n }\n throw new CommandError(\n 'BAD_ARGS',\n `Platform \"${platform}\" is not configured to use the Metro bundler in the project Expo config, or is missing from the supported platforms in the platforms array: [${exp.platforms?.join(\n ', '\n )}].`\n );\n }\n\n return platform;\n };\n\n const knownPlatforms = ['android', 'ios', 'web'] as Platform[];\n const assertPlatformIsKnown = (platform: string): Platform => {\n if (!knownPlatforms.includes(platform as Platform)) {\n throw new CommandError(\n `Unsupported platform \"${platform}\". Options are: ${knownPlatforms.join(',')},all`\n );\n }\n\n return platform as Platform;\n };\n\n return (\n platform\n // Expand `all` to all available platforms.\n .map((platform) => (platform === 'all' ? Object.keys(platformsAvailable) : platform))\n .flat()\n // Remove duplicated platforms\n .filter((platform, index, list) => list.indexOf(platform) === index)\n // Assert platforms are valid\n .map((platform) => assertPlatformIsKnown(platform))\n .map((platform) => assertPlatformBundler(platform))\n );\n}\n\nexport async function resolveOptionsAsync(projectRoot: string, args: any): Promise<Options> {\n const { exp } = getConfig(projectRoot, { skipPlugins: true, skipSDKVersionRequirement: true });\n const platformBundlers = getPlatformBundlers(projectRoot, exp);\n\n const platforms = resolvePlatformOption(exp, platformBundlers, args['--platform']);\n\n // --source-maps can be true, \"external\", or \"inline\"\n const sourceMapsArg = args['--source-maps'];\n const sourceMaps = !!sourceMapsArg;\n const inlineSourceMaps = sourceMapsArg === 'inline';\n\n return {\n platforms,\n hostedNative: !!args['--unstable-hosted-native'],\n outputDir: args['--output-dir'] ?? 'dist',\n minify: !args['--no-minify'],\n bytecode: !args['--no-bytecode'],\n clear: !!args['--clear'],\n dev: !!args['--dev'],\n maxWorkers: args['--max-workers'],\n dumpAssetmap: !!args['--dump-assetmap'],\n sourceMaps,\n inlineSourceMaps,\n skipSSG: !!args['--no-ssg'] || !!args['--api-only'],\n };\n}\n"],"names":["resolveOptionsAsync","resolvePlatformOption","exp","platformBundlers","platform","platformsAvailable","Object","fromEntries","entries","filter","bundler","platforms","includes","keys","length","CommandError","assertPlatformBundler","join","knownPlatforms","assertPlatformIsKnown","map","flat","index","list","indexOf","projectRoot","args","getConfig","skipPlugins","skipSDKVersionRequirement","getPlatformBundlers","sourceMapsArg","sourceMaps","inlineSourceMaps","hostedNative","outputDir","minify","bytecode","clear","dev","maxWorkers","dumpAssetmap","skipSSG"],"mappings":";;;;;;;;;;;QAiFsBA;eAAAA;;QA1DNC;eAAAA;;;;yBAtBU;;;;;;kCAGU;wBACP;AAkBtB,SAASA,sBACdC,GAAe,EACfC,gBAAkC,EAClCC,WAAqB;IAAC;CAAM;IAE5B,MAAMC,qBAAgDC,OAAOC,WAAW,CACtED,OAAOE,OAAO,CAACL,kBAAkBM,MAAM,CACrC,CAAC,CAACL,UAAUM,QAAQ;YAA4BR;eAAvBQ,YAAY,aAAWR,iBAAAA,IAAIS,SAAS,qBAAbT,eAAeU,QAAQ,CAACR;;IAI5E,IAAI,CAACE,OAAOO,IAAI,CAACR,oBAAoBS,MAAM,EAAE;QAC3C,MAAM,IAAIC,oBAAY,CACpB,CAAC,gFAAgF,CAAC;IAEtF;IAEA,MAAMC,wBAAwB,CAACZ;QAC7B,IAAI,CAACC,kBAAkB,CAACD,SAAS,EAAE;gBAC5BF,gBAMkKA;YANvK,IAAI,GAACA,iBAAAA,IAAIS,SAAS,qBAAbT,eAAeU,QAAQ,CAACR,cAAaA,aAAa,OAAO;gBAC5D,0DAA0D;gBAC1D,OAAOA;YACT;YACA,MAAM,IAAIW,oBAAY,CACpB,YACA,CAAC,UAAU,EAAEX,SAAS,6IAA6I,GAAEF,kBAAAA,IAAIS,SAAS,qBAAbT,gBAAee,IAAI,CACtL,MACA,EAAE,CAAC;QAET;QAEA,OAAOb;IACT;IAEA,MAAMc,iBAAiB;QAAC;QAAW;QAAO;KAAM;IAChD,M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cAAc,CAAC,CAACf,IAAI,CAAC,kBAAkB;QACvCM;QACAC;QACAS,SAAS,CAAC,CAAChB,IAAI,CAAC,WAAW,IAAI,CAAC,CAACA,IAAI,CAAC,aAAa;IACrD;AACF"}
1
+ {"version":3,"sources":["../../../src/export/resolveOptions.ts"],"sourcesContent":["import type { Platform } from '@expo/config';\nimport { getConfig, getPlatformsFromConfig } from '@expo/config';\n\nimport type { PlatformBundlers } from '../start/server/platformBundlers';\nimport { getPlatformBundlers } from '../start/server/platformBundlers';\nimport { CommandError } from '../utils/errors';\n\nexport type Options = {\n outputDir: string;\n platforms: Platform[];\n maxWorkers?: number;\n dev: boolean;\n clear: boolean;\n minify: boolean;\n bytecode: boolean;\n dumpAssetmap: boolean;\n sourceMaps: boolean;\n inlineSourceMaps: boolean;\n skipSSG: boolean;\n hostedNative: boolean;\n};\n\n/** Returns an array of platforms based on the input platform identifier and runtime constraints. */\nexport function resolvePlatformOption(\n configPlatforms: Platform[],\n platformBundlers: PlatformBundlers,\n platform: string[] = ['all']\n): Platform[] {\n const platformsAvailable: Partial<PlatformBundlers> = Object.fromEntries(\n Object.entries(platformBundlers).filter(\n ([platform, bundler]) => bundler === 'metro' && configPlatforms.includes(platform as Platform)\n )\n );\n\n if (!Object.keys(platformsAvailable).length) {\n throw new CommandError(\n `No platforms are configured to use the Metro bundler in the project Expo config.`\n );\n }\n\n const assertPlatformBundler = (platform: Platform): Platform => {\n if (!platformsAvailable[platform]) {\n if (!configPlatforms.includes(platform) && platform === 'web') {\n // Pass through so the more robust error message is shown.\n return platform;\n }\n throw new CommandError(\n 'BAD_ARGS',\n `Platform \"${platform}\" is not configured to use the Metro bundler in the project Expo config, or is missing from the supported platforms in the platforms array: [${configPlatforms.join(\n ', '\n )}].`\n );\n }\n\n return platform;\n };\n\n const knownPlatforms = ['android', 'ios', 'web', 'tvos', 'macos'] as Platform[];\n const assertPlatformIsKnown = (platform: string): Platform => {\n if (!knownPlatforms.includes(platform as Platform)) {\n throw new CommandError(\n `Unsupported platform \"${platform}\". Options are: ${knownPlatforms.join(',')},all`\n );\n }\n\n return platform as Platform;\n };\n\n return (\n platform\n // Expand `all` to all available platforms.\n .map((platform) => (platform === 'all' ? Object.keys(platformsAvailable) : platform))\n .flat()\n // Remove duplicated platforms\n .filter((platform, index, list) => list.indexOf(platform) === index)\n // Assert platforms are valid\n .map((platform) => assertPlatformIsKnown(platform))\n .map((platform) => assertPlatformBundler(platform))\n );\n}\n\nexport async function resolveOptionsAsync(projectRoot: string, args: any): Promise<Options> {\n const { exp } = getConfig(projectRoot, { skipPlugins: true, skipSDKVersionRequirement: true });\n const platformBundlers = getPlatformBundlers(projectRoot, exp);\n\n const platformsFromConfig = getPlatformsFromConfig(projectRoot, exp);\n const platforms = resolvePlatformOption(\n platformsFromConfig,\n platformBundlers,\n args['--platform']\n );\n\n // --source-maps can be true, \"external\", or \"inline\"\n const sourceMapsArg = args['--source-maps'];\n const sourceMaps = !!sourceMapsArg;\n const inlineSourceMaps = sourceMapsArg === 'inline';\n\n return {\n platforms,\n hostedNative: !!args['--unstable-hosted-native'],\n outputDir: args['--output-dir'] ?? 'dist',\n minify: !args['--no-minify'],\n bytecode: !args['--no-bytecode'],\n clear: !!args['--clear'],\n dev: !!args['--dev'],\n maxWorkers: args['--max-workers'],\n dumpAssetmap: !!args['--dump-assetmap'],\n sourceMaps,\n inlineSourceMaps,\n skipSSG: !!args['--no-ssg'] || !!args['--api-only'],\n };\n}\n"],"names":["resolveOptionsAsync","resolvePlatformOption","configPlatforms","platformBundlers","platform","platformsAvailable","Object","fromEntries","entries","filter","bundler","includes","keys","length","CommandError","assertPlatformBundler","join","knownPlatforms","assertPlatformIsKnown","map","flat","index","list","indexOf","projectRoot","args","exp","getConfig","skipPlugins","skipSDKVersionRequirement","getPlatformBundlers","platformsFromConfig","getPlatformsFromConfig","platforms","sourceMapsArg","sourceMaps","inlineSourceMaps","hostedNative","outputDir","minify","bytecode","clear","dev","maxWorkers","dumpAssetmap","skipSSG"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D,6BAA6B;KAC5BF,GAAG,CAAC,CAACf,WAAac,sBAAsBd,WACxCe,GAAG,CAAC,CAACf,WAAaW,sBAAsBX;AAE/C;AAEO,eAAeJ,oBAAoBwB,WAAmB,EAAEC,IAAS;IACtE,MAAM,EAAEC,GAAG,EAAE,GAAGC,IAAAA,mBAAS,EAACH,aAAa;QAAEI,aAAa;QAAMC,2BAA2B;IAAK;IAC5F,MAAM1B,mBAAmB2B,IAAAA,qCAAmB,EAACN,aAAaE;IAE1D,MAAMK,sBAAsBC,IAAAA,gCAAsB,EAACR,aAAaE;IAChE,MAAMO,YAAYhC,sBAChB8B,qBACA5B,kBACAsB,IAAI,CAAC,aAAa;IAGpB,qDAAqD;IACrD,MAAMS,gBAAgBT,IAAI,CAAC,gBAAgB;IAC3C,MAAMU,aAAa,CAAC,CAACD;IACrB,MAAME,mBAAmBF,kBAAkB;IAE3C,OAAO;QACLD;QACAI,cAAc,CAAC,CAACZ,IAAI,CAAC,2BAA2B;QAChDa,WAAWb,IAAI,CAAC,eAAe,IAAI;QACnCc,QAAQ,CAACd,IAAI,CAAC,cAAc;QAC5Be,UAAU,CAACf,IAAI,CAAC,gBAAgB;QAChCgB,OAAO,CAAC,CAAChB,IAAI,CAAC,UAAU;QACxBiB,KAAK,CAAC,CAACjB,IAAI,CAAC,QAAQ;QACpBkB,YAAYlB,IAAI,CAAC,gBAAgB;QACjCmB,cAAc,CAAC,CAACnB,IAAI,CAAC,kBAAkB;QACvCU;QACAC;QACAS,SAAS,CAAC,CAACpB,IAAI,CAAC,WAAW,IAAI,CAAC,CAACA,IAAI,CAAC,aAAa;IACrD;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/export/saveAssets.ts"],"sourcesContent":["/**\n * Copyright © 2023 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 type { AssetData } from '@expo/metro/metro';\nimport type { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport path from 'path';\n\nimport { Log } from '../log';\nimport { env } from '../utils/env';\n\nlet bytesFormatter: Intl.NumberFormat | undefined | null;\n\nconst prettyBytes = (bytes: number): string => {\n try {\n if (bytesFormatter === undefined && typeof Intl === 'object') {\n bytesFormatter = new Intl.NumberFormat('en', {\n notation: 'compact',\n style: 'unit',\n unit: 'byte',\n unitDisplay: 'narrow',\n });\n }\n if (bytesFormatter != null) {\n return bytesFormatter.format(bytes);\n }\n } catch {\n bytesFormatter = null;\n }\n // Fall back if ICU is unavailable, which is rare but possible with custom Node.js builds\n if (bytes >= 900_000) {\n return `${(bytes / 1_000_000).toFixed(1)}MB`;\n } else if (bytes >= 900) {\n return `${(bytes / 1_000).toFixed(1)}KB`;\n } else {\n return `${bytes}B`;\n }\n};\n\nconst BLT = '\\u203A';\n\nexport type BundleOptions = {\n entryPoint: string;\n platform: 'android' | 'ios' | 'web';\n dev?: boolean;\n minify?: boolean;\n bytecode: boolean;\n sourceMapUrl?: string;\n sourcemaps?: boolean;\n};\n\nexport type BundleAssetWithFileHashes = AssetData & {\n fileHashes: string[]; // added by the hashAssets asset plugin\n};\n\nexport type BundleOutput = {\n artifacts: SerialAsset[];\n assets: readonly BundleAssetWithFileHashes[];\n};\n\nexport type ManifestAsset = { fileHashes: string[]; files: string[]; hash: string };\n\nexport type Asset = ManifestAsset | BundleAssetWithFileHashes;\n\nexport type ExportAssetDescriptor = {\n contents: string | Buffer;\n originFilename?: string;\n /** An identifier for grouping together variations of the same asset. */\n assetId?: string;\n /** Expo Router route path for formatting the HTML output. */\n routeId?: string;\n /** Expo Router route path for formatting the middleware function output. */\n middlewareId?: string;\n /** Expo Router API route path for formatting the server function output. */\n apiRouteId?: string;\n /** Expo Router route path for formatting the RSC output. */\n rscId?: string;\n /** Expo Router route path for formatting the loader module output. */\n loaderId?: string;\n /** A key for grouping together output files by server- or client-side. */\n targetDomain?: 'server' | 'client';\n};\n\nexport type ExportAssetMap = Map<string, ExportAssetDescriptor>;\n\nexport async function persistMetroFilesAsync(files: ExportAssetMap, outputDir: string) {\n if (!files.size) {\n return;\n }\n await fs.promises.mkdir(path.join(outputDir), { recursive: true });\n\n // Test fixtures:\n // Log.log(\n // JSON.stringify(\n // Object.fromEntries([...files.entries()].map(([k, v]) => [k, { ...v, contents: '' }]))\n // )\n // );\n\n const assetEntries: [string, ExportAssetDescriptor][] = [];\n const apiRouteEntries: [string, ExportAssetDescriptor][] = [];\n const middlewareEntries: [string, ExportAssetDescriptor][] = [];\n const routeEntries: [string, ExportAssetDescriptor][] = [];\n const rscEntries: [string, ExportAssetDescriptor][] = [];\n const loaderEntries: [string, ExportAssetDescriptor][] = [];\n const remainingEntries: [string, ExportAssetDescriptor][] = [];\n\n let hasServerOutput = false;\n for (const asset of files.entries()) {\n hasServerOutput = hasServerOutput || asset[1].targetDomain === 'server';\n if (asset[1].assetId) assetEntries.push(asset);\n else if (asset[1].routeId != null) routeEntries.push(asset);\n else if (asset[1].middlewareId != null) middlewareEntries.push(asset);\n else if (asset[1].apiRouteId != null) apiRouteEntries.push(asset);\n else if (asset[1].rscId != null) rscEntries.push(asset);\n else if (asset[1].loaderId != null) loaderEntries.push(asset);\n else remainingEntries.push(asset);\n }\n\n const groups = groupBy(assetEntries, ([, { assetId }]) => assetId!);\n\n const contentSize = (contents: string | Buffer) => {\n const length =\n typeof contents === 'string' ? Buffer.byteLength(contents, 'utf8') : contents.length;\n return length;\n };\n\n const sizeStr = (contents: string | Buffer) => {\n const length = contentSize(contents);\n const size = chalk.gray`(${prettyBytes(length)})`;\n return size;\n };\n\n // TODO: If any Expo Router is used, then use a new style which is more simple:\n // `chalk.gray(/path/to/) + chalk.cyan('route')`\n // | index.html (1.2kb)\n // | /path\n // | other.html (1.2kb)\n\n const isExpoRouter = routeEntries.length;\n\n // Phase out printing all the assets as users can simply check the file system for more info.\n const showAdditionalInfo = !isExpoRouter || env.EXPO_DEBUG;\n\n const assetGroups = [...groups.entries()].sort((a, b) => a[0].localeCompare(b[0])) as [\n string,\n [string, ExportAssetDescriptor][],\n ][];\n\n if (showAdditionalInfo) {\n if (assetGroups.length) {\n const totalAssets = assetGroups.reduce((sum, [, assets]) => sum + assets.length, 0);\n\n Log.log('');\n Log.log(chalk.bold`${BLT} Assets (${totalAssets}):`);\n\n for (const [assetId, assets] of assetGroups) {\n const averageContentSize =\n assets.reduce((sum, [, { contents }]) => sum + contentSize(contents), 0) / assets.length;\n Log.log(\n assetId,\n chalk.gray(\n `(${[\n assets.length > 1 ? `${assets.length} variations` : '',\n `${prettyBytes(averageContentSize)}`,\n ]\n .filter(Boolean)\n .join(' | ')})`\n )\n );\n }\n }\n }\n\n const bundles: Map<string, [string, ExportAssetDescriptor][]> = new Map();\n const other: [string, ExportAssetDescriptor][] = [];\n\n remainingEntries.forEach(([filepath, asset]) => {\n if (!filepath.match(/_expo\\/(server|static)\\//)) {\n other.push([filepath, asset]);\n } else {\n const platform = filepath.match(/_expo\\/static\\/js\\/([^/]+)\\//)?.[1] ?? 'web';\n if (!bundles.has(platform)) bundles.set(platform, []);\n\n bundles.get(platform)!.push([filepath, asset]);\n }\n });\n\n [...bundles.entries()].forEach(([platform, assets]) => {\n Log.log('');\n Log.log(chalk.bold`${BLT} ${platform} bundles (${assets.length}):`);\n\n const allAssets = assets.sort((a, b) => a[0].localeCompare(b[0]));\n while (allAssets.length) {\n const [filePath, asset] = allAssets.shift()!;\n Log.log(filePath, sizeStr(asset.contents));\n if (filePath.match(/\\.(js|hbc)$/)) {\n // Get source map\n const sourceMapIndex = allAssets.findIndex(([fp]) => fp === filePath + '.map');\n if (sourceMapIndex !== -1) {\n const [sourceMapFilePath, sourceMapAsset] = allAssets.splice(sourceMapIndex, 1)[0]!;\n Log.log(chalk.gray(sourceMapFilePath), sizeStr(sourceMapAsset.contents));\n }\n }\n }\n });\n\n if (showAdditionalInfo && other.length) {\n Log.log('');\n Log.log(chalk.bold`${BLT} Files (${other.length}):`);\n\n for (const [filePath, asset] of other.sort((a, b) => a[0].localeCompare(b[0]))) {\n Log.log(filePath, sizeStr(asset.contents));\n }\n }\n\n if (rscEntries.length) {\n Log.log('');\n Log.log(chalk.bold`${BLT} React Server Components (${rscEntries.length}):`);\n\n for (const [filePath, assets] of rscEntries.sort((a, b) => a[0].length - b[0].length)) {\n const id = assets.rscId!;\n Log.log(\n '/' + (id === '' ? chalk.gray(' (index)') : id),\n sizeStr(assets.contents),\n chalk.gray(filePath)\n );\n }\n }\n\n if (routeEntries.length) {\n Log.log('');\n Log.log(chalk.bold`${BLT} Static routes (${routeEntries.length}):`);\n\n for (const [, assets] of routeEntries.sort((a, b) => a[0].length - b[0].length)) {\n const id = assets.routeId!;\n Log.log('/' + (id === '' ? chalk.gray(' (index)') : id), sizeStr(assets.contents));\n }\n }\n\n if (apiRouteEntries.length) {\n const apiRoutesWithoutSourcemaps = apiRouteEntries.filter(\n (route) => !route[0].endsWith('.map')\n );\n Log.log('');\n Log.log(chalk.bold`${BLT} API routes (${apiRoutesWithoutSourcemaps.length}):`);\n\n for (const [apiRouteFilename, assets] of apiRoutesWithoutSourcemaps.sort(\n (a, b) => a[0].length - b[0].length\n )) {\n const id = assets.apiRouteId!;\n const hasSourceMap = apiRouteEntries.find(\n ([filename, route]) =>\n filename !== apiRouteFilename &&\n route.apiRouteId === assets.apiRouteId &&\n filename.endsWith('.map')\n );\n Log.log(\n id === '' ? chalk.gray(' (index)') : id,\n sizeStr(assets.contents),\n hasSourceMap ? chalk.gray(`(source map ${sizeStr(hasSourceMap[1].contents)})`) : ''\n );\n }\n }\n\n if (middlewareEntries.length) {\n const middlewareWithoutSourcemaps = middlewareEntries.filter(\n (route) => !route[0].endsWith('.map')\n );\n Log.log('');\n Log.log(chalk.bold`${BLT} Middleware:`);\n\n for (const [middlewareFilename, assets] of middlewareWithoutSourcemaps.sort(\n (a, b) => a[0].length - b[0].length\n )) {\n const id = assets.middlewareId!;\n const hasSourceMap = middlewareEntries.find(\n ([filename, route]) =>\n filename !== middlewareFilename &&\n route.middlewareId === assets.middlewareId &&\n filename.endsWith('.map')\n );\n Log.log(\n id,\n sizeStr(assets.contents),\n hasSourceMap ? chalk.gray(`(source map ${sizeStr(hasSourceMap[1].contents)})`) : ''\n );\n }\n }\n\n if (loaderEntries.length) {\n const loadersWithoutSourcemaps = loaderEntries.filter((entry) => !entry[0].endsWith('.map'));\n Log.log('');\n Log.log(chalk.bold`${BLT} Loaders (${loadersWithoutSourcemaps.length}):`);\n\n for (const [loaderFilename, assets] of loadersWithoutSourcemaps.sort(\n (a, b) => a[0].length - b[0].length\n )) {\n const id = assets.loaderId!;\n const hasSourceMap = loaderEntries.find(\n ([filename, entry]) =>\n filename !== loaderFilename &&\n entry.loaderId === assets.loaderId &&\n filename.endsWith('.map')\n );\n Log.log(\n id === '/' ? '/ ' + chalk.gray('(index)') : id,\n sizeStr(assets.contents),\n hasSourceMap ? chalk.gray(`(source map ${sizeStr(hasSourceMap[1].contents)})`) : ''\n );\n }\n }\n\n // Decouple logging from writing for better performance.\n\n await Promise.all(\n [...files.entries()]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(async ([file, { contents, targetDomain }]) => {\n // NOTE: Only use `targetDomain` if we have at least one server asset\n const domain = (hasServerOutput && targetDomain) || '';\n const outputPath = path.join(outputDir, domain, file);\n await fs.promises.mkdir(path.dirname(outputPath), { recursive: true });\n await fs.promises.writeFile(outputPath, contents);\n })\n );\n\n Log.log('');\n}\n\nfunction groupBy<T>(array: T[], key: (item: T) => string): Map<string, T[]> {\n const map = new Map<string, T[]>();\n array.forEach((item) => {\n const group = key(item);\n const list = map.get(group) ?? [];\n list.push(item);\n map.set(group, list);\n });\n return map;\n}\n\n// TODO: Move source map modification to the serializer\nexport function getFilesFromSerialAssets(\n resources: SerialAsset[],\n {\n includeSourceMaps,\n files = new Map(),\n platform,\n isServerHosted = platform === 'web',\n }: {\n includeSourceMaps: boolean;\n files?: ExportAssetMap;\n platform?: string;\n isServerHosted?: boolean;\n }\n) {\n resources.forEach((resource) => {\n if (resource.type === 'css-external') {\n return;\n }\n files.set(resource.filename, {\n contents: resource.source,\n originFilename: resource.originFilename,\n targetDomain: isServerHosted ? 'client' : undefined,\n });\n });\n\n return files;\n}\n"],"names":["getFilesFromSerialAssets","persistMetroFilesAsync","bytesFormatter","prettyBytes","bytes","undefined","Intl","NumberFormat","notation","style","unit","unitDisplay","format","toFixed","BLT","files","outputDir","size","fs","promises","mkdir","path","join","recursive","assetEntries","apiRouteEntries","middlewareEntries","routeEntries","rscEntries","loaderEntries","remainingEntries","hasServerOutput","asset","entries","targetDomain","assetId","push","routeId","middlewareId","apiRouteId","rscId","loaderId","groups","groupBy","contentSize","contents","length","Buffer","byteLength","sizeStr","chalk","gray","isExpoRouter","showAdditionalInfo","env","EXPO_DEBUG","assetGroups","sort","a","b","localeCompare","totalAssets","reduce","sum","assets","Log","log","bold","averageContentSize","filter","Boolean","bundles","Map","other","forEach","filepath","match","platform","has","set","get","allAssets","filePath","shift","sourceMapIndex","findIndex","fp","sourceMapFilePath","sourceMapAsset","splice","id","apiRoutesWithoutSourcemaps","route","endsWith","apiRouteFilename","hasSourceMap","find","filename","middlewareWithoutSourcemaps","middlewareFilename","loadersWithoutSourcemaps","entry","loaderFilename","Promise","all","map","file","domain","outputPath","dirname","writeFile","array","key","item","group","list","resources","includeSourceMaps","isServerHosted","resource","type","source","originFilename"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;QAoVeA;eAAAA;;QAhQMC;eAAAA;;;;gEAjFJ;;;;;;;gEACH;;;;;;;gEACE;;;;;;qBAEG;qBACA;;;;;;AAEpB,IAAIC;AAEJ,MAAMC,cAAc,CAACC;IACnB,IAAI;QACF,IAAIF,mBAAmBG,aAAa,OAAOC,SAAS,UAAU;YAC5DJ,iBAAiB,IAAII,KAAKC,YAAY,CAAC,MAAM;gBAC3CC,UAAU;gBACVC,OAAO;gBACPC,MAAM;gBACNC,aAAa;YACf;QACF;QACA,IAAIT,kBAAkB,MAAM;YAC1B,OAAOA,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AAE,GAAKD,EAAEE,aAAa,CAACD,IACnC8C,GAAG,CAAC,OAAO,CAACC,MAAM,EAAE7D,QAAQ,EAAEX,YAAY,EAAE,CAAC;QAC5C,qEAAqE;QACrE,MAAMyE,SAAS,AAAC5E,mBAAmBG,gBAAiB;QACpD,MAAM0E,aAAavF,eAAI,CAACC,IAAI,CAACN,WAAW2F,QAAQD;QAChD,MAAMxF,aAAE,CAACC,QAAQ,CAACC,KAAK,CAACC,eAAI,CAACwF,OAAO,CAACD,aAAa;YAAErF,WAAW;QAAK;QACpE,MAAML,aAAE,CAACC,QAAQ,CAAC2F,SAAS,CAACF,YAAY/D;IAC1C;IAGJoB,QAAG,CAACC,GAAG,CAAC;AACV;AAEA,SAASvB,QAAWoE,KAAU,EAAEC,GAAwB;IACtD,MAAMP,MAAM,IAAIjC;IAChBuC,MAAMrC,OAAO,CAAC,CAACuC;QACb,MAAMC,QAAQF,IAAIC;QAClB,MAAME,OAAOV,IAAIzB,GAAG,CAACkC,UAAU,EAAE;QACjCC,KAAK/E,IAAI,CAAC6E;QACVR,IAAI1B,GAAG,CAACmC,OAAOC;IACjB;IACA,OAAOV;AACT;AAGO,SAASzG,yBACdoH,SAAwB,EACxB,EACEC,iBAAiB,EACjBtG,QAAQ,IAAIyD,KAAK,EACjBK,QAAQ,EACRyC,iBAAiBzC,aAAa,KAAK,EAMpC;IAEDuC,UAAU1C,OAAO,CAAC,CAAC6C;QACjB,IAAIA,SAASC,IAAI,KAAK,gBAAgB;YACpC;QACF;QACAzG,MAAMgE,GAAG,CAACwC,SAAStB,QAAQ,EAAE;YAC3BpD,UAAU0E,SAASE,MAAM;YACzBC,gBAAgBH,SAASG,cAAc;YACvCxF,cAAcoF,iBAAiB,WAAWjH;QAC5C;IACF;IAEA,OAAOU;AACT"}
1
+ {"version":3,"sources":["../../../src/export/saveAssets.ts"],"sourcesContent":["/**\n * Copyright © 2023 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 type { Platform } from '@expo/config';\nimport type { AssetData } from '@expo/metro/metro';\nimport type { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport path from 'path';\n\nimport { Log } from '../log';\nimport { env } from '../utils/env';\n\nlet bytesFormatter: Intl.NumberFormat | undefined | null;\n\nconst prettyBytes = (bytes: number): string => {\n try {\n if (bytesFormatter === undefined && typeof Intl === 'object') {\n bytesFormatter = new Intl.NumberFormat('en', {\n notation: 'compact',\n style: 'unit',\n unit: 'byte',\n unitDisplay: 'narrow',\n });\n }\n if (bytesFormatter != null) {\n return bytesFormatter.format(bytes);\n }\n } catch {\n bytesFormatter = null;\n }\n // Fall back if ICU is unavailable, which is rare but possible with custom Node.js builds\n if (bytes >= 900_000) {\n return `${(bytes / 1_000_000).toFixed(1)}MB`;\n } else if (bytes >= 900) {\n return `${(bytes / 1_000).toFixed(1)}KB`;\n } else {\n return `${bytes}B`;\n }\n};\n\nconst BLT = '\\u203A';\n\nexport type BundleOptions = {\n entryPoint: string;\n platform: Platform;\n dev?: boolean;\n minify?: boolean;\n bytecode: boolean;\n sourceMapUrl?: string;\n sourcemaps?: boolean;\n};\n\nexport type BundleAssetWithFileHashes = AssetData & {\n fileHashes: string[]; // added by the hashAssets asset plugin\n};\n\nexport type BundleOutput = {\n artifacts: SerialAsset[];\n assets: readonly BundleAssetWithFileHashes[];\n};\n\nexport type ManifestAsset = { fileHashes: string[]; files: string[]; hash: string };\n\nexport type Asset = ManifestAsset | BundleAssetWithFileHashes;\n\nexport type ExportAssetDescriptor = {\n contents: string | Buffer;\n originFilename?: string;\n /** An identifier for grouping together variations of the same asset. */\n assetId?: string;\n /** Expo Router route path for formatting the HTML output. */\n routeId?: string;\n /** Expo Router route path for formatting the middleware function output. */\n middlewareId?: string;\n /** Expo Router API route path for formatting the server function output. */\n apiRouteId?: string;\n /** Expo Router route path for formatting the RSC output. */\n rscId?: string;\n /** Expo Router route path for formatting the loader module output. */\n loaderId?: string;\n /** A key for grouping together output files by server- or client-side. */\n targetDomain?: 'server' | 'client';\n};\n\nexport type ExportAssetMap = Map<string, ExportAssetDescriptor>;\n\nexport async function persistMetroFilesAsync(files: ExportAssetMap, outputDir: string) {\n if (!files.size) {\n return;\n }\n await fs.promises.mkdir(path.join(outputDir), { recursive: true });\n\n // Test fixtures:\n // Log.log(\n // JSON.stringify(\n // Object.fromEntries([...files.entries()].map(([k, v]) => [k, { ...v, contents: '' }]))\n // )\n // );\n\n const assetEntries: [string, ExportAssetDescriptor][] = [];\n const apiRouteEntries: [string, ExportAssetDescriptor][] = [];\n const middlewareEntries: [string, ExportAssetDescriptor][] = [];\n const routeEntries: [string, ExportAssetDescriptor][] = [];\n const rscEntries: [string, ExportAssetDescriptor][] = [];\n const loaderEntries: [string, ExportAssetDescriptor][] = [];\n const remainingEntries: [string, ExportAssetDescriptor][] = [];\n\n let hasServerOutput = false;\n for (const asset of files.entries()) {\n hasServerOutput = hasServerOutput || asset[1].targetDomain === 'server';\n if (asset[1].assetId) assetEntries.push(asset);\n else if (asset[1].routeId != null) routeEntries.push(asset);\n else if (asset[1].middlewareId != null) middlewareEntries.push(asset);\n else if (asset[1].apiRouteId != null) apiRouteEntries.push(asset);\n else if (asset[1].rscId != null) rscEntries.push(asset);\n else if (asset[1].loaderId != null) loaderEntries.push(asset);\n else remainingEntries.push(asset);\n }\n\n const groups = groupBy(assetEntries, ([, { assetId }]) => assetId!);\n\n const contentSize = (contents: string | Buffer) => {\n const length =\n typeof contents === 'string' ? Buffer.byteLength(contents, 'utf8') : contents.length;\n return length;\n };\n\n const sizeStr = (contents: string | Buffer) => {\n const length = contentSize(contents);\n const size = chalk.gray`(${prettyBytes(length)})`;\n return size;\n };\n\n // TODO: If any Expo Router is used, then use a new style which is more simple:\n // `chalk.gray(/path/to/) + chalk.cyan('route')`\n // | index.html (1.2kb)\n // | /path\n // | other.html (1.2kb)\n\n const isExpoRouter = routeEntries.length;\n\n // Phase out printing all the assets as users can simply check the file system for more info.\n const showAdditionalInfo = !isExpoRouter || env.EXPO_DEBUG;\n\n const assetGroups = [...groups.entries()].sort((a, b) => a[0].localeCompare(b[0])) as [\n string,\n [string, ExportAssetDescriptor][],\n ][];\n\n if (showAdditionalInfo) {\n if (assetGroups.length) {\n const totalAssets = assetGroups.reduce((sum, [, assets]) => sum + assets.length, 0);\n\n Log.log('');\n Log.log(chalk.bold`${BLT} Assets (${totalAssets}):`);\n\n for (const [assetId, assets] of assetGroups) {\n const averageContentSize =\n assets.reduce((sum, [, { contents }]) => sum + contentSize(contents), 0) / assets.length;\n Log.log(\n assetId,\n chalk.gray(\n `(${[\n assets.length > 1 ? `${assets.length} variations` : '',\n `${prettyBytes(averageContentSize)}`,\n ]\n .filter(Boolean)\n .join(' | ')})`\n )\n );\n }\n }\n }\n\n const bundles: Map<string, [string, ExportAssetDescriptor][]> = new Map();\n const other: [string, ExportAssetDescriptor][] = [];\n\n remainingEntries.forEach(([filepath, asset]) => {\n if (!filepath.match(/_expo\\/(server|static)\\//)) {\n other.push([filepath, asset]);\n } else {\n const platform = filepath.match(/_expo\\/static\\/js\\/([^/]+)\\//)?.[1] ?? 'web';\n if (!bundles.has(platform)) bundles.set(platform, []);\n\n bundles.get(platform)!.push([filepath, asset]);\n }\n });\n\n [...bundles.entries()].forEach(([platform, assets]) => {\n Log.log('');\n Log.log(chalk.bold`${BLT} ${platform} bundles (${assets.length}):`);\n\n const allAssets = assets.sort((a, b) => a[0].localeCompare(b[0]));\n while (allAssets.length) {\n const [filePath, asset] = allAssets.shift()!;\n Log.log(filePath, sizeStr(asset.contents));\n if (filePath.match(/\\.(js|hbc)$/)) {\n // Get source map\n const sourceMapIndex = allAssets.findIndex(([fp]) => fp === filePath + '.map');\n if (sourceMapIndex !== -1) {\n const [sourceMapFilePath, sourceMapAsset] = allAssets.splice(sourceMapIndex, 1)[0]!;\n Log.log(chalk.gray(sourceMapFilePath), sizeStr(sourceMapAsset.contents));\n }\n }\n }\n });\n\n if (showAdditionalInfo && other.length) {\n Log.log('');\n Log.log(chalk.bold`${BLT} Files (${other.length}):`);\n\n for (const [filePath, asset] of other.sort((a, b) => a[0].localeCompare(b[0]))) {\n Log.log(filePath, sizeStr(asset.contents));\n }\n }\n\n if (rscEntries.length) {\n Log.log('');\n Log.log(chalk.bold`${BLT} React Server Components (${rscEntries.length}):`);\n\n for (const [filePath, assets] of rscEntries.sort((a, b) => a[0].length - b[0].length)) {\n const id = assets.rscId!;\n Log.log(\n '/' + (id === '' ? chalk.gray(' (index)') : id),\n sizeStr(assets.contents),\n chalk.gray(filePath)\n );\n }\n }\n\n if (routeEntries.length) {\n Log.log('');\n Log.log(chalk.bold`${BLT} Static routes (${routeEntries.length}):`);\n\n for (const [, assets] of routeEntries.sort((a, b) => a[0].length - b[0].length)) {\n const id = assets.routeId!;\n Log.log('/' + (id === '' ? chalk.gray(' (index)') : id), sizeStr(assets.contents));\n }\n }\n\n if (apiRouteEntries.length) {\n const apiRoutesWithoutSourcemaps = apiRouteEntries.filter(\n (route) => !route[0].endsWith('.map')\n );\n Log.log('');\n Log.log(chalk.bold`${BLT} API routes (${apiRoutesWithoutSourcemaps.length}):`);\n\n for (const [apiRouteFilename, assets] of apiRoutesWithoutSourcemaps.sort(\n (a, b) => a[0].length - b[0].length\n )) {\n const id = assets.apiRouteId!;\n const hasSourceMap = apiRouteEntries.find(\n ([filename, route]) =>\n filename !== apiRouteFilename &&\n route.apiRouteId === assets.apiRouteId &&\n filename.endsWith('.map')\n );\n Log.log(\n id === '' ? chalk.gray(' (index)') : id,\n sizeStr(assets.contents),\n hasSourceMap ? chalk.gray(`(source map ${sizeStr(hasSourceMap[1].contents)})`) : ''\n );\n }\n }\n\n if (middlewareEntries.length) {\n const middlewareWithoutSourcemaps = middlewareEntries.filter(\n (route) => !route[0].endsWith('.map')\n );\n Log.log('');\n Log.log(chalk.bold`${BLT} Middleware:`);\n\n for (const [middlewareFilename, assets] of middlewareWithoutSourcemaps.sort(\n (a, b) => a[0].length - b[0].length\n )) {\n const id = assets.middlewareId!;\n const hasSourceMap = middlewareEntries.find(\n ([filename, route]) =>\n filename !== middlewareFilename &&\n route.middlewareId === assets.middlewareId &&\n filename.endsWith('.map')\n );\n Log.log(\n id,\n sizeStr(assets.contents),\n hasSourceMap ? chalk.gray(`(source map ${sizeStr(hasSourceMap[1].contents)})`) : ''\n );\n }\n }\n\n if (loaderEntries.length) {\n const loadersWithoutSourcemaps = loaderEntries.filter((entry) => !entry[0].endsWith('.map'));\n Log.log('');\n Log.log(chalk.bold`${BLT} Loaders (${loadersWithoutSourcemaps.length}):`);\n\n for (const [loaderFilename, assets] of loadersWithoutSourcemaps.sort(\n (a, b) => a[0].length - b[0].length\n )) {\n const id = assets.loaderId!;\n const hasSourceMap = loaderEntries.find(\n ([filename, entry]) =>\n filename !== loaderFilename &&\n entry.loaderId === assets.loaderId &&\n filename.endsWith('.map')\n );\n Log.log(\n id === '/' ? '/ ' + chalk.gray('(index)') : id,\n sizeStr(assets.contents),\n hasSourceMap ? chalk.gray(`(source map ${sizeStr(hasSourceMap[1].contents)})`) : ''\n );\n }\n }\n\n // Decouple logging from writing for better performance.\n\n await Promise.all(\n [...files.entries()]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(async ([file, { contents, targetDomain }]) => {\n // NOTE: Only use `targetDomain` if we have at least one server asset\n const domain = (hasServerOutput && targetDomain) || '';\n const outputPath = path.join(outputDir, domain, file);\n await fs.promises.mkdir(path.dirname(outputPath), { recursive: true });\n await fs.promises.writeFile(outputPath, contents);\n })\n );\n\n Log.log('');\n}\n\nfunction groupBy<T>(array: T[], key: (item: T) => string): Map<string, T[]> {\n const map = new Map<string, T[]>();\n array.forEach((item) => {\n const group = key(item);\n const list = map.get(group) ?? [];\n list.push(item);\n map.set(group, list);\n });\n return map;\n}\n\n// TODO: Move source map modification to the serializer\nexport function getFilesFromSerialAssets(\n resources: SerialAsset[],\n {\n includeSourceMaps,\n files = new Map(),\n platform,\n isServerHosted = platform === 'web',\n }: {\n includeSourceMaps: boolean;\n files?: ExportAssetMap;\n platform?: string;\n isServerHosted?: boolean;\n }\n) {\n resources.forEach((resource) => {\n if (resource.type === 'css-external') {\n return;\n }\n files.set(resource.filename, {\n contents: resource.source,\n originFilename: resource.originFilename,\n targetDomain: isServerHosted ? 'client' : undefined,\n });\n });\n\n return files;\n}\n"],"names":["getFilesFromSerialAssets","persistMetroFilesAsync","bytesFormatter","prettyBytes","bytes","undefined","Intl","NumberFormat","notation","style","unit","unitDisplay","format","toFixed","BLT","files","outputDir","size","fs","promises","mkdir","path","join","recursive","assetEntries","apiRouteEntries","middlewareEntries","routeEntries","rscEntries","loaderEntries","remainingEntries","hasServerOutput","asset","entries","targetDomain","assetId","push","routeId","middlewareId","apiRouteId","rscId","loaderId","groups","groupBy","contentSize","contents","length","Buffer","byteLength","sizeStr","chalk","gray","isExpoRouter","showAdditionalInfo","env","EXPO_DEBUG","assetGroups","sort","a","b","localeCompare","totalAssets","reduce","sum","assets","Log","log","bold","averageContentSize","filter","Boolean","bundles","Map","other","forEach","filepath","match","platform","has","set","get","allAssets","filePath","shift","sourceMapIndex","findIndex","fp","sourceMapFilePath","sourceMapAsset","splice","id","apiRoutesWithoutSourcemaps","route","endsWith","apiRouteFilename","hasSourceMap","find","filename","middlewareWithoutSourcemaps","middlewareFilename","loadersWithoutSourcemaps","entry","loaderFilename","Promise","all","map","file","domain","outputPath","dirname","writeFile","array","key","item","group","list","resources","includeSourceMaps","isServerHosted","resource","type","source","originFilename"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;QAqVeA;eAAAA;;QAhQMC;eAAAA;;;;gEAjFJ;;;;;;;gEACH;;;;;;;gEACE;;;;;;qBAEG;qBACA;;;;;;AAEpB,IAAIC;AAEJ,MAAMC,cAAc,CAACC;IACnB,IAAI;QACF,IAAIF,mBAAmBG,aAAa,OAAOC,SAAS,UAAU;YAC5DJ,iBAAiB,IAAII,KAAKC,YAAY,CAAC,MAAM;gBAC3CC,UAA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Y_DEPENDENCIES = [
52
52
  const AUTOLINKING_PLATFORMS = [
53
53
  'android',
54
54
  'ios',
55
- 'web'
55
+ 'web',
56
+ 'tvos',
57
+ 'macos'
56
58
  ];
57
59
  const escapeDependencyName = (dependency)=>dependency.replace(/[*.?()[\]]/g, (x)=>`\\${x}`);
58
60
  const _dependenciesToRegex = (dependencies)=>new RegExp(`^(${dependencies.map(escapeDependencyName).join('|')})($|/.*)`);
59
61
  const getAutolinkingExports = ()=>require('expo/internal/unstable-autolinking-exports');
60
- const toPlatformModuleDescription = (dependencies, platform)=>{
62
+ const toPlatformModuleDescription = (dependencies, platform, supportPackage)=>{
61
63
  const resolvedModulePaths = {};
62
64
  const resolvedModuleNames = [];
63
65
  for(const dependencyName in dependencies){
@@ -67,11 +69,17 @@ const toPlatformModuleDescription = (dependencies, platform)=>{
67
69
  resolvedModulePaths[dependency.name] = dependency.path;
68
70
  }
69
71
  }
72
+ // Redirect `react-native` to the platform's support package
73
+ const moduleNameRewrites = {};
74
+ if (supportPackage && supportPackage !== 'react-native' && resolvedModulePaths[supportPackage]) {
75
+ moduleNameRewrites['react-native'] = supportPackage;
76
+ }
70
77
  debug(`Sticky resolution for ${platform} registered ${resolvedModuleNames.length} resolutions:`, resolvedModuleNames);
71
78
  return {
72
79
  platform,
73
80
  moduleTestRe: _dependenciesToRegex(resolvedModuleNames),
74
- resolvedModulePaths
81
+ resolvedModulePaths,
82
+ moduleNameRewrites
75
83
  };
76
84
  };
77
85
  async function createAutolinkingModuleResolverInput({ platforms, projectRoot }) {
@@ -83,7 +91,8 @@ async function createAutolinkingModuleResolverInput({ platforms, projectRoot })
83
91
  return AUTOLINKING_PLATFORMS.includes(platform);
84
92
  }).map(async (platform)=>{
85
93
  const dependencies = await autolinking.scanDependencyResolutionsForPlatform(linker, platform, KNOWN_STICKY_DEPENDENCIES);
86
- const moduleDescription = toPlatformModuleDescription(dependencies, platform);
94
+ const supportPackage = autolinking.getSupportPackageForPlatform(platform);
95
+ const moduleDescription = toPlatformModuleDescription(dependencies, platform, supportPackage);
87
96
  return [
88
97
  platform,
89
98
  moduleDescription
@@ -108,15 +117,19 @@ function createAutolinkingModuleResolver(input, { getStrictResolver }) {
108
117
  const moduleDescription = input[platform];
109
118
  const moduleMatch = moduleDescription.moduleTestRe.exec(moduleName);
110
119
  if (moduleMatch) {
111
- const resolvedModulePath = moduleDescription.resolvedModulePaths[moduleMatch[1]] || moduleName;
112
- // We instead resolve as if it was a dependency from within the module (self-require/import)
120
+ var _moduleDescription_moduleNameRewrites;
121
+ const matchedName = moduleMatch[1];
122
+ const rewriteTarget = (_moduleDescription_moduleNameRewrites = moduleDescription.moduleNameRewrites) == null ? void 0 : _moduleDescription_moduleNameRewrites[matchedName];
123
+ const resolvedModuleName = rewriteTarget != null ? rewriteTarget + moduleMatch[2] : moduleName;
124
+ const resolvedModulePath = moduleDescription.resolvedModulePaths[rewriteTarget ?? matchedName] || resolvedModuleName;
125
+ // We instead resolve as if it was a dependency from within the (target) module
113
126
  const context = {
114
127
  ...immutableContext,
115
128
  nodeModulesPaths: [],
116
129
  originModulePath: resolvedModulePath
117
130
  };
118
- const res = getStrictResolver(context, platform)(moduleName);
119
- debug(`Sticky resolution for ${platform}: ${moduleName} -> from: ${resolvedModulePath}`);
131
+ const res = getStrictResolver(context, platform)(resolvedModuleName);
132
+ debug(`Sticky resolution for ${platform}: ${moduleName} -> ${resolvedModuleName} (from: ${resolvedModulePath})`);
120
133
  return res;
121
134
  }
122
135
  return null;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/createExpoAutolinkingResolver.ts"],"sourcesContent":["import type { ResolutionContext } from '@expo/metro/metro-resolver';\nimport type { ResolutionResult as AutolinkingResolutionResult } from 'expo-modules-autolinking/exports';\n\nimport type { StrictResolverFactory } from './withMetroMultiPlatform';\nimport type { ExpoCustomMetroResolver } from './withMetroResolvers';\n\nconst debug = require('debug')(\n 'expo:start:server:metro:autolinking-resolver'\n) as typeof console.log;\n\n// This is a list of known modules we want to always include in sticky resolution\n// Specifying these skips platform- and module-specific checks and always includes them in the output\nconst KNOWN_STICKY_DEPENDENCIES = [\n // NOTE: react and react-dom aren't native modules, but must also be deduplicated in bundles\n 'react',\n 'react-dom',\n // NOTE: react-native won't be in autolinking output, since it's special\n // We include it here manually, since we know it should be an unduplicated direct dependency\n 'react-native',\n // NOTE: We may redirect dependencies from react-native to react-native-web. This fails if\n // a sub-dependency cannot access react-native-web, so we define it here\n 'react-native-web',\n // Peer dependencies from expo\n 'react-native-webview',\n '@expo/dom-webview',\n // Dependencies from expo\n 'expo-asset',\n 'expo-constants',\n 'expo-file-system',\n 'expo-font',\n 'expo-keep-awake',\n 'expo-modules-core',\n // Peer dependencies from expo-router\n 'react-native-gesture-handler',\n 'react-native-reanimated',\n // Has a context that needs to be deduplicated\n '@react-navigation/core',\n '@react-navigation/native',\n];\n\nconst AUTOLINKING_PLATFORMS = ['android', 'ios', 'web'] as const;\n\nexport type AutolinkingPlatform = (typeof AUTOLINKING_PLATFORMS)[number];\n\nconst escapeDependencyName = (dependency: string) =>\n dependency.replace(/[*.?()[\\]]/g, (x) => `\\\\${x}`);\n\n/** Converts a list of module names to a regex that may either match bare module names or sub-modules of modules */\nexport const _dependenciesToRegex = (dependencies: string[]) =>\n new RegExp(`^(${dependencies.map(escapeDependencyName).join('|')})($|/.*)`);\n\nconst getAutolinkingExports = (): typeof import('expo/internal/unstable-autolinking-exports') =>\n require('expo/internal/unstable-autolinking-exports');\n\ninterface PlatformModuleDescription {\n platform: AutolinkingPlatform;\n moduleTestRe: RegExp;\n resolvedModulePaths: Record<string, string>;\n}\n\nconst toPlatformModuleDescription = (\n dependencies: AutolinkingResolutionResult,\n platform: AutolinkingPlatform\n): PlatformModuleDescription => {\n const resolvedModulePaths: Record<string, string> = {};\n const resolvedModuleNames: string[] = [];\n for (const dependencyName in dependencies) {\n const dependency = dependencies[dependencyName];\n if (dependency) {\n resolvedModuleNames.push(dependency.name);\n resolvedModulePaths[dependency.name] = dependency.path;\n }\n }\n debug(\n `Sticky resolution for ${platform} registered ${resolvedModuleNames.length} resolutions:`,\n resolvedModuleNames\n );\n return {\n platform,\n moduleTestRe: _dependenciesToRegex(resolvedModuleNames),\n resolvedModulePaths,\n };\n};\n\nexport type AutolinkingModuleResolverInput = {\n [platform in AutolinkingPlatform]?: PlatformModuleDescription;\n};\n\nexport async function createAutolinkingModuleResolverInput({\n platforms,\n projectRoot,\n}: {\n projectRoot: string;\n platforms: string[];\n}): Promise<AutolinkingModuleResolverInput> {\n const autolinking = getAutolinkingExports();\n const linker = autolinking.makeCachedDependenciesLinker({ projectRoot });\n\n return Object.fromEntries(\n await Promise.all(\n platforms\n .filter((platform): platform is AutolinkingPlatform => {\n return AUTOLINKING_PLATFORMS.includes(platform as any);\n })\n .map(async (platform) => {\n const dependencies = await autolinking.scanDependencyResolutionsForPlatform(\n linker,\n platform,\n KNOWN_STICKY_DEPENDENCIES\n );\n const moduleDescription = toPlatformModuleDescription(dependencies, platform);\n return [platform, moduleDescription] satisfies [\n AutolinkingPlatform,\n PlatformModuleDescription,\n ];\n })\n )\n ) as AutolinkingModuleResolverInput;\n}\n\nexport function createAutolinkingModuleResolver(\n input: AutolinkingModuleResolverInput | undefined,\n { getStrictResolver }: { getStrictResolver: StrictResolverFactory }\n): ExpoCustomMetroResolver | undefined {\n if (!input) {\n return undefined;\n }\n\n const fileSpecifierRe = /^[\\\\/]|^\\.\\.?(?:$|[\\\\/])/i;\n const isAutolinkingPlatform = (platform: string | null): platform is AutolinkingPlatform =>\n !!platform && (input as any)[platform] != null;\n\n return function requestStickyModule(immutableContext, moduleName, platform) {\n // NOTE(@kitten): We currently don't include Web. The `expo-doctor` check already warns\n // about duplicates, and we can try to add Web later on. We should expand expo-modules-autolinking\n // properly to support web first however\n if (!isAutolinkingPlatform(platform)) {\n return null;\n } else if (fileSpecifierRe.test(moduleName)) {\n return null;\n }\n\n const moduleDescription = input[platform]!;\n const moduleMatch = moduleDescription.moduleTestRe.exec(moduleName);\n if (moduleMatch) {\n const resolvedModulePath =\n moduleDescription.resolvedModulePaths[moduleMatch[1]!] || moduleName;\n // We instead resolve as if it was a dependency from within the module (self-require/import)\n const context: ResolutionContext = {\n ...immutableContext,\n nodeModulesPaths: [],\n originModulePath: resolvedModulePath,\n };\n const res = getStrictResolver(context, platform)(moduleName);\n debug(`Sticky resolution for ${platform}: ${moduleName} -> from: ${resolvedModulePath}`);\n return res;\n }\n\n return null;\n };\n}\n"],"names":["_dependenciesToRegex","createAutolinkingModuleResolver","createAutolinkingModuleResolverInput","debug","require","KNOWN_STICKY_DEPENDENCIES","AUTOLINKING_PLATFORMS","escapeDependencyName","dependency","replace","x","dependencies","RegExp","map","join","getAutolinkingExports","toPlatformModuleDescription","platform","resolvedModulePaths","resolvedModuleNames","dependencyName","push","name","path","length","moduleTestRe","platforms","projectRoot","autolinking","linker","makeCachedDependenciesLinker","Object","fromEntries","Promise","all","filter","includes","scanDependencyResolutionsForPlatform","moduleDescription","input","getStrictResolver","undefined","fileSpecifierRe","isAutolinkingPlatform","requestStickyModule","immutableContext","moduleName","test","moduleMatch","exec","resolvedModulePath","context","nodeModulesPaths","originModulePath","res"],"mappings":";;;;;;;;;;;QAgDaA;eAAAA;;QAwEGC;eAAAA;;QAhCMC;eAAAA;;;AAlFtB,MAAMC,QAAQC,QAAQ,SACpB;AAGF,iFAAiF;AACjF,qGAAqG;AACrG,MAAMC,4BAA4B;IAChC,4FAA4F;IAC5F;IACA;IACA,wEAAwE;IACxE,4FAA4F;IAC5F;IACA,0FAA0F;IAC1F,wEAAwE;IACxE;IACA,8BAA8B;IAC9B;IACA;IACA,yBAAyB;IACzB;IACA;IACA;IACA;IACA;IACA;IACA,qCAAqC;IACrC;IACA;IACA,8CAA8C;IAC9C;IACA;CACD;AAED,MAAMC,wBAAwB;IAAC;IAAW;IAAO;CAAM;AAIvD,MAAMC,uBAAuB,CAACC,aAC5BA,WAAWC,OAAO,CAAC,eAAe,CAACC,IAAM,CAAC,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AC,CAACA,YAAY,AAACsB,KAAa,CAACtB,SAAS,IAAI;IAE5C,OAAO,SAAS2B,oBAAoBC,gBAAgB,EAAEC,UAAU,EAAE7B,QAAQ;QACxE,uFAAuF;QACvF,kGAAkG;QAClG,wCAAwC;QACxC,IAAI,CAAC0B,sBAAsB1B,WAAW;YACpC,OAAO;QACT,OAAO,IAAIyB,gBAAgBK,IAAI,CAACD,aAAa;YAC3C,OAAO;QACT;QAEA,MAAMR,oBAAoBC,KAAK,CAACtB,SAAS;QACzC,MAAM+B,cAAcV,kBAAkBb,YAAY,CAACwB,IAAI,CAACH;QACxD,IAAIE,aAAa;YACf,MAAME,qBACJZ,kBAAkBpB,mBAAmB,CAAC8B,WAAW,CAAC,EAAE,CAAE,IAAIF;YAC5D,4FAA4F;YAC5F,MAAMK,UAA6B;gBACjC,GAAGN,gBAAgB;gBACnBO,kBAAkB,EAAE;gBACpBC,kBAAkBH;YACpB;YACA,MAAMI,MAAMd,kBAAkBW,SAASlC,UAAU6B;YACjD3C,MAAM,CAAC,sBAAsB,EAAEc,SAAS,EAAE,EAAE6B,WAAW,UAAU,EAAEI,oBAAoB;YACvF,OAAOI;QACT;QAEA,OAAO;IACT;AACF"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/createExpoAutolinkingResolver.ts"],"sourcesContent":["import type { Platform } from '@expo/config';\nimport type { ResolutionContext } from '@expo/metro/metro-resolver';\nimport type { ResolutionResult as AutolinkingResolutionResult } from 'expo-modules-autolinking/exports';\n\nimport type { StrictResolverFactory } from './withMetroMultiPlatform';\nimport type { ExpoCustomMetroResolver } from './withMetroResolvers';\n\nconst debug = require('debug')(\n 'expo:start:server:metro:autolinking-resolver'\n) as typeof console.log;\n\n// This is a list of known modules we want to always include in sticky resolution\n// Specifying these skips platform- and module-specific checks and always includes them in the output\nconst KNOWN_STICKY_DEPENDENCIES = [\n // NOTE: react and react-dom aren't native modules, but must also be deduplicated in bundles\n 'react',\n 'react-dom',\n // NOTE: react-native won't be in autolinking output, since it's special\n // We include it here manually, since we know it should be an unduplicated direct dependency\n 'react-native',\n // NOTE: We may redirect dependencies from react-native to react-native-web. This fails if\n // a sub-dependency cannot access react-native-web, so we define it here\n 'react-native-web',\n // Peer dependencies from expo\n 'react-native-webview',\n '@expo/dom-webview',\n // Dependencies from expo\n 'expo-asset',\n 'expo-constants',\n 'expo-file-system',\n 'expo-font',\n 'expo-keep-awake',\n 'expo-modules-core',\n // Peer dependencies from expo-router\n 'react-native-gesture-handler',\n 'react-native-reanimated',\n // Has a context that needs to be deduplicated\n '@react-navigation/core',\n '@react-navigation/native',\n];\n\nconst AUTOLINKING_PLATFORMS: readonly Platform[] = ['android', 'ios', 'web', 'tvos', 'macos'];\n\nexport type AutolinkingPlatform = Platform;\n\nconst escapeDependencyName = (dependency: string) =>\n dependency.replace(/[*.?()[\\]]/g, (x) => `\\\\${x}`);\n\n/** Converts a list of module names to a regex that may either match bare module names or sub-modules of modules */\nexport const _dependenciesToRegex = (dependencies: string[]) =>\n new RegExp(`^(${dependencies.map(escapeDependencyName).join('|')})($|/.*)`);\n\nconst getAutolinkingExports = (): typeof import('expo/internal/unstable-autolinking-exports') =>\n require('expo/internal/unstable-autolinking-exports');\n\ninterface PlatformModuleDescription {\n platform: AutolinkingPlatform;\n moduleTestRe: RegExp;\n resolvedModulePaths: Record<string, string>;\n moduleNameRewrites: Record<string, string | undefined>;\n}\n\nconst toPlatformModuleDescription = (\n dependencies: AutolinkingResolutionResult,\n platform: AutolinkingPlatform,\n supportPackage: string | null\n): PlatformModuleDescription => {\n const resolvedModulePaths: Record<string, string> = {};\n const resolvedModuleNames: string[] = [];\n for (const dependencyName in dependencies) {\n const dependency = dependencies[dependencyName];\n if (dependency) {\n resolvedModuleNames.push(dependency.name);\n resolvedModulePaths[dependency.name] = dependency.path;\n }\n }\n // Redirect `react-native` to the platform's support package\n const moduleNameRewrites: Record<string, string | undefined> = {};\n if (supportPackage && supportPackage !== 'react-native' && resolvedModulePaths[supportPackage]) {\n moduleNameRewrites['react-native'] = supportPackage;\n }\n debug(\n `Sticky resolution for ${platform} registered ${resolvedModuleNames.length} resolutions:`,\n resolvedModuleNames\n );\n return {\n platform,\n moduleTestRe: _dependenciesToRegex(resolvedModuleNames),\n resolvedModulePaths,\n moduleNameRewrites,\n };\n};\n\nexport type AutolinkingModuleResolverInput = {\n [platform in AutolinkingPlatform]?: PlatformModuleDescription;\n};\n\nexport async function createAutolinkingModuleResolverInput({\n platforms,\n projectRoot,\n}: {\n projectRoot: string;\n platforms: string[];\n}): Promise<AutolinkingModuleResolverInput> {\n const autolinking = getAutolinkingExports();\n const linker = autolinking.makeCachedDependenciesLinker({ projectRoot });\n\n return Object.fromEntries(\n await Promise.all(\n platforms\n .filter((platform): platform is AutolinkingPlatform => {\n return AUTOLINKING_PLATFORMS.includes(platform as any);\n })\n .map(async (platform) => {\n const dependencies = await autolinking.scanDependencyResolutionsForPlatform(\n linker,\n platform,\n KNOWN_STICKY_DEPENDENCIES\n );\n const supportPackage = autolinking.getSupportPackageForPlatform(platform);\n const moduleDescription = toPlatformModuleDescription(\n dependencies,\n platform,\n supportPackage\n );\n return [platform, moduleDescription] satisfies [\n AutolinkingPlatform,\n PlatformModuleDescription,\n ];\n })\n )\n ) as AutolinkingModuleResolverInput;\n}\n\nexport function createAutolinkingModuleResolver(\n input: AutolinkingModuleResolverInput | undefined,\n { getStrictResolver }: { getStrictResolver: StrictResolverFactory }\n): ExpoCustomMetroResolver | undefined {\n if (!input) {\n return undefined;\n }\n\n const fileSpecifierRe = /^[\\\\/]|^\\.\\.?(?:$|[\\\\/])/i;\n const isAutolinkingPlatform = (platform: string | null): platform is AutolinkingPlatform =>\n !!platform && (input as any)[platform] != null;\n\n return function requestStickyModule(immutableContext, moduleName, platform) {\n // NOTE(@kitten): We currently don't include Web. The `expo-doctor` check already warns\n // about duplicates, and we can try to add Web later on. We should expand expo-modules-autolinking\n // properly to support web first however\n if (!isAutolinkingPlatform(platform)) {\n return null;\n } else if (fileSpecifierRe.test(moduleName)) {\n return null;\n }\n\n const moduleDescription = input[platform]!;\n const moduleMatch = moduleDescription.moduleTestRe.exec(moduleName);\n if (moduleMatch) {\n const matchedName = moduleMatch[1]!;\n const rewriteTarget = moduleDescription.moduleNameRewrites?.[matchedName];\n const resolvedModuleName =\n rewriteTarget != null ? rewriteTarget + moduleMatch[2]! : moduleName;\n const resolvedModulePath =\n moduleDescription.resolvedModulePaths[rewriteTarget ?? matchedName] || resolvedModuleName;\n // We instead resolve as if it was a dependency from within the (target) module\n const context: ResolutionContext = {\n ...immutableContext,\n nodeModulesPaths: [],\n originModulePath: resolvedModulePath,\n };\n const res = getStrictResolver(context, platform)(resolvedModuleName);\n debug(\n `Sticky resolution for ${platform}: ${moduleName} -> ${resolvedModuleName} (from: ${resolvedModulePath})`\n );\n return res;\n }\n\n return null;\n };\n}\n"],"names":["_dependenciesToRegex","createAutolinkingModuleResolver","createAutolinkingModuleResolverInput","debug","require","KNOWN_STICKY_DEPENDENCIES","AUTOLINKING_PLATFORMS","escapeDependencyName","dependency","replace","x","dependencies","RegExp","map","join","getAutolinkingExports","toPlatformModuleDescription","platform","supportPackage","resolvedModulePaths","resolvedModuleNames","dependencyName","push","name","path","moduleNameRewrites","length","moduleTestRe","platforms","projectRoot","autolinking","linker","makeCachedDependenciesLinker","Object","fromEntries","Promise","all","filter","includes","scanDependencyResolutionsForPlatform","getSupportPackageForPlatform","moduleDescription","input","getStrictResolver","undefined","fileSpecifierRe","isAutolinkingPlatform","requestStickyModule","immutableContext","moduleName","test","moduleMatch","exec","matchedName","rewriteTarget","resolvedModuleName","resolvedModulePath","context","nodeModulesPaths","originModulePath","res"],"mappings":";;;;;;;;;;;QAiDaA;eAAAA;;QAqFGC;eAAAA;;QArCMC;eAAAA;;;AA1FtB,MAAMC,QAAQC,QAAQ,SACpB;AAGF,iFAAiF;AACjF,qGAAqG;AACrG,MAAMC,4BAA4B;IAChC,4FAA4F;IAC5F;IACA;IACA,wEAAwE;IACxE,4FAA4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AgB;gBACnBU,kBAAkB,EAAE;gBACpBC,kBAAkBH;YACpB;YACA,MAAMI,MAAMjB,kBAAkBc,SAASxC,UAAUsC;YACjDpD,MACE,CAAC,sBAAsB,EAAEc,SAAS,EAAE,EAAEgC,WAAW,IAAI,EAAEM,mBAAmB,QAAQ,EAAEC,mBAAmB,CAAC,CAAC;YAE3G,OAAOI;QACT;QAEA,OAAO;IACT;AACF"}
@@ -201,8 +201,11 @@ async function loadMetroConfigAsync(projectRoot, options, { exp, isExporting, ge
201
201
  // folder is different (presumably a parent) we're in a monorepo
202
202
  const serverRoot = (0, _paths().getMetroServerRoot)(projectRoot);
203
203
  const isWorkspace = serverRoot !== projectRoot;
204
- // Autolinking Module Resolution will be enabled by default when we're in a monorepo
205
- const autolinkingModuleResolutionEnabled = ((_exp_experiments = exp.experiments) == null ? void 0 : _exp_experiments.autolinkingModuleResolution) ?? isWorkspace;
204
+ // Out-of-tree platforms (tvos/macos) rely on the autolinking module resolver to remap the
205
+ // react-native package to their support package, and require autolinking module resolution
206
+ const targetsOutOfTreePlatform = (0, _config().getPlatformsFromConfig)(projectRoot, exp).some((platform)=>platform === 'tvos' || platform === 'macos');
207
+ // Autolinking Module Resolution is enabled by default in a monorepo or for out-of-tree platforms.
208
+ const autolinkingModuleResolutionEnabled = ((_exp_experiments = exp.experiments) == null ? void 0 : _exp_experiments.autolinkingModuleResolution) ?? (isWorkspace || targetsOutOfTreePlatform);
206
209
  const serverActionsEnabled = ((_exp_experiments1 = exp.experiments) == null ? void 0 : _exp_experiments1.reactServerFunctions) ?? _env.env.EXPO_UNSTABLE_SERVER_FUNCTIONS;
207
210
  const serverComponentsEnabled = !!((_exp_experiments2 = exp.experiments) == null ? void 0 : _exp_experiments2.reactServerComponentRoutes);
208
211
  if (serverActionsEnabled) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/instantiateMetro.ts"],"sourcesContent":["import { type ExpoConfig, getConfig } from '@expo/config';\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport type { Reporter } from '@expo/metro/metro';\nimport type Bundler from '@expo/metro/metro/Bundler';\nimport type { ReadOnlyGraph } from '@expo/metro/metro/DeltaBundler';\nimport type { TransformOptions } from '@expo/metro/metro/DeltaBundler/Worker';\nimport type { Client as MetroHmrClient } from '@expo/metro/metro/HmrServer';\nimport type MetroHmrServer from '@expo/metro/metro/HmrServer';\nimport RevisionNotFoundError from '@expo/metro/metro/IncrementalBundler/RevisionNotFoundError';\nimport type MetroServer from '@expo/metro/metro/Server';\nimport formatBundlingError from '@expo/metro/metro/lib/formatBundlingError';\nimport { Terminal } from '@expo/metro/metro-core';\nimport type { createStableModuleIdFactory } from '@expo/metro-config';\nimport { loadUserConfig } from '@expo/metro-config';\nimport { patchTransformFileForPackedMaps } from '@expo/metro-config/build/serializer/packedMap';\nimport { patchMetroSourceMapStringForPackedMaps } from '@expo/metro-config/build/serializer/sourceMap';\nimport chalk from 'chalk';\nimport type http from 'http';\nimport path from 'path';\n\nimport { createDevToolsPluginWebsocketEndpoint } from './DevToolsPluginWebsocketEndpoint';\nimport type { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { MetroTerminalReporter } from './MetroTerminalReporter';\nimport { replaceMetroFileMap } from './createFileMap-fork';\nimport { attachAtlasAsync } from './debugging/attachAtlas';\nimport { createDebugMiddleware } from './debugging/createDebugMiddleware';\nimport { createMetroMiddleware } from './dev-server/createMetroMiddleware';\nimport { runServer, type ServerAddressInfo, type SecureServerOptions } from './runServer-fork';\nimport { withMetroMultiPlatformAsync } from './withMetroMultiPlatform';\nimport { events, shouldReduceLogs } from '../../../events';\nimport { Log } from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { createCorsMiddleware } from '../middleware/CorsMiddleware';\nimport { createJsInspectorMiddleware } from '../middleware/inspector/createJsInspectorMiddleware';\nimport { prependMiddleware } from '../middleware/mutations';\nimport { getPlatformBundlers } from '../platformBundlers';\n\n// prettier-ignore\nexport const event = events('metro', (t) => [\n t.event<'config', {\n serverRoot: string;\n projectRoot: string;\n exporting: boolean;\n flags: {\n autolinkingModuleResolution: boolean;\n serverActions: boolean;\n serverComponents: boolean;\n reactCompiler: boolean;\n optimizeGraph?: boolean;\n treeshaking?: boolean;\n logbox?: boolean;\n };\n }>(),\n t.event<'instantiate', {\n atlas: boolean;\n workers: number | null;\n host: string | null;\n port: number | null;\n }>(),\n]);\n\n// NOTE(@kitten): We pass a custom createStableModuleIdFactory function into the Metro module ID factory sometimes\ninterface MetroServerWithModuleIdMod extends MetroServer {\n _createModuleId: ReturnType<typeof createStableModuleIdFactory> & ((path: string) => number);\n}\ninterface MetroHmrServerWithModuleIdMod extends MetroHmrServer<MetroHmrClient> {\n _createModuleId: ReturnType<typeof createStableModuleIdFactory> & ((path: string) => number);\n}\n\n// From expo/dev-server but with ability to use custom logger.\ntype MessageSocket = {\n broadcast: (method: string, params?: Record<string, any> | undefined) => void;\n};\n\n// TODO(@kitten): We assign this here to run server-side code bundled by metro\n// It's not isolated into a worker thread yet\n// Check `metro-require/require.ts` for how this setting is used\ndeclare namespace globalThis {\n let __requireCycleIgnorePatterns: readonly RegExp[] | undefined;\n}\n\nfunction asWritable<T>(input: T): { -readonly [K in keyof T]: T[K] } {\n return input;\n}\n\n/**\n * Extends Metro's Terminal to intercept all console methods so they don't\n * corrupt the progress bar status lines.\n *\n * console.log/info are routed through terminal.log() (stdout, managed).\n * console.warn/error are routed through logStderr() which clears the\n * status from stdout before writing to stderr, then restores it.\n * Without this, unmanaged stderr writes shift the cursor and cause\n * progress bars to get stuck as permanent output.\n */\nclass LogRespectingTerminal extends Terminal {\n #stderrQueue: string[] = [];\n #drainingStderr = false;\n\n constructor(stream: import('node:net').Socket | import('node:stream').Writable) {\n super(stream, { ttyPrint: true });\n\n const sendLog = (...msg: any[]) => {\n if (!msg.length) {\n this.log('');\n } else {\n const [format, ...args] = msg;\n this.log(format, ...args);\n }\n // Flush the logs to the terminal immediately so logs at the end of the process are not lost.\n this.flush();\n };\n\n const sendStderr = (...msg: any[]) => {\n if (!msg.length) {\n this.logStderr('');\n } else {\n const [format, ...args] = msg;\n this.logStderr(require('util').format(format, ...args));\n }\n };\n\n console.log = sendLog;\n console.info = sendLog;\n console.warn = sendStderr;\n console.error = sendStderr;\n\n // NOTE(@kitten): We flush the stderr queue immediately when we're about to exit\n process.on('exit', () => {\n if (!this.#drainingStderr && this.#stderrQueue.length) {\n this.#drainingStderr = true;\n this.status('');\n const lines = this.#stderrQueue.splice(0);\n process.stderr.write(lines.join('\\n') + '\\n');\n }\n });\n }\n\n /** Write to stderr without corrupting Terminal's cursor tracking. */\n logStderr(line: string): void {\n if (!(process.stdout as any).isTTY) {\n process.stderr.write(line + '\\n');\n return;\n }\n this.#stderrQueue.push(line);\n this.#drainStderr();\n }\n\n async #drainStderr(): Promise<void> {\n if (this.#drainingStderr) return;\n this.#drainingStderr = true;\n\n while (this.#stderrQueue.length > 0) {\n // Clear status, flush to ensure it's removed from screen\n const prev = this.status('');\n await this.flush();\n\n // Write to stderr while status is cleared\n const lines = this.#stderrQueue.splice(0);\n process.stderr.write(lines.join('\\n') + '\\n');\n\n // Restore status\n this.status(prev);\n }\n\n this.#drainingStderr = false;\n }\n}\n\n// Share one instance of Terminal for all instances of Metro.\nconst terminal = new LogRespectingTerminal(process.stdout);\n\ninterface LoadMetroConfigOptions {\n maxWorkers?: number;\n port?: number;\n reporter?: Reporter;\n resetCache?: boolean;\n}\n\nexport async function loadMetroConfigAsync(\n projectRoot: string,\n options: LoadMetroConfigOptions,\n {\n exp,\n isExporting,\n getMetroBundler,\n }: { exp: ExpoConfig; isExporting: boolean; getMetroBundler: () => Bundler }\n) {\n let reportEvent: ((event: any) => void) | undefined;\n\n // We're resolving a monorepo root, higher up than the `projectRoot`. If this\n // folder is different (presumably a parent) we're in a monorepo\n const serverRoot = getMetroServerRoot(projectRoot);\n const isWorkspace = serverRoot !== projectRoot;\n\n // Autolinking Module Resolution will be enabled by default when we're in a monorepo\n const autolinkingModuleResolutionEnabled =\n exp.experiments?.autolinkingModuleResolution ?? isWorkspace;\n\n const serverActionsEnabled =\n exp.experiments?.reactServerFunctions ?? env.EXPO_UNSTABLE_SERVER_FUNCTIONS;\n const serverComponentsEnabled = !!exp.experiments?.reactServerComponentRoutes;\n if (serverActionsEnabled) {\n process.env.EXPO_UNSTABLE_SERVER_FUNCTIONS = '1';\n }\n\n // NOTE: Enable all the experimental Metro flags when RSC is enabled.\n if (serverComponentsEnabled || serverActionsEnabled) {\n process.env.EXPO_USE_METRO_REQUIRE = '1';\n }\n\n if (exp.experiments?.reactCanary) {\n Log.warn(`React 19 is enabled by default. Remove unused experiments.reactCanary flag.`);\n }\n\n const terminalReporter = new MetroTerminalReporter(serverRoot, terminal);\n\n let config = await loadUserConfig({\n projectRoot,\n serverRoot,\n // NOTE: Allow external tools to override the metro config. This is considered internal and unstable\n overrideConfigPath: env.EXPO_OVERRIDE_METRO_CONFIG ?? undefined,\n });\n\n config = {\n ...config,\n // See: `overrideConfigWithArguments` https://github.com/facebook/metro/blob/5059e26/packages/metro-config/src/loadConfig.js#L274-L339\n // Compare to `LoadOptions` type (disregard `reporter` as we don't expose this)\n resetCache: !!options.resetCache,\n maxWorkers: options.maxWorkers ?? config.maxWorkers,\n server: {\n ...config.server,\n port: options.port ?? config.server.port,\n },\n // Force-override the reporter\n reporter: {\n update(event) {\n terminalReporter.update(event);\n if (reportEvent) {\n reportEvent(event);\n }\n },\n },\n };\n\n // On-Demand Filesystem is enabled by default\n // TODO(@kitten): Add to config-types JSON schema\n const onDemandFilesystem = exp.experiments?.onDemandFilesystem ?? true;\n asWritable(config.resolver).unstable_onDemandFilesystem = onDemandFilesystem;\n\n globalThis.__requireCycleIgnorePatterns = config.resolver?.requireCycleIgnorePatterns;\n\n if (isExporting) {\n // This token will be used in the asset plugin to ensure the path is correct for writing locally.\n asWritable(config.transformer).publicPath = `/assets?export_path=${\n (exp.experiments?.baseUrl ?? '') + '/assets'\n }`;\n } else {\n asWritable(config.transformer).publicPath = '/assets/?unstable_path=.';\n }\n\n const platformBundlers = getPlatformBundlers(projectRoot, exp);\n const reduceLogs = shouldReduceLogs();\n\n const reactCompilerEnabled = !!exp.experiments?.reactCompiler;\n if (!reduceLogs && reactCompilerEnabled) {\n Log.log(chalk.gray`React Compiler enabled`);\n }\n\n if (!reduceLogs && autolinkingModuleResolutionEnabled) {\n Log.log(chalk.gray`Expo Autolinking module resolution enabled`);\n }\n\n if (env.EXPO_UNSTABLE_TREE_SHAKING && !env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n throw new CommandError(\n 'EXPO_UNSTABLE_TREE_SHAKING requires EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH to be enabled.'\n );\n }\n\n if (!reduceLogs && env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n Log.warn(`Experimental bundle optimization is enabled.`);\n }\n if (!reduceLogs && env.EXPO_UNSTABLE_TREE_SHAKING) {\n Log.warn(`Experimental tree shaking is enabled.`);\n }\n if (!reduceLogs && env.EXPO_UNSTABLE_LOG_BOX) {\n Log.warn(`Experimental Expo LogBox is enabled.`);\n }\n\n if (!reduceLogs && serverActionsEnabled) {\n Log.warn(\n `React Server Functions (beta) are enabled. Route rendering mode: ${exp.experiments?.reactServerComponentRoutes ? 'server' : 'client'}`\n );\n }\n\n config = await withMetroMultiPlatformAsync(projectRoot, {\n config,\n exp,\n platformBundlers,\n serverRoot,\n isTsconfigPathsEnabled: exp.experiments?.tsconfigPaths ?? true,\n isAutolinkingResolverEnabled: autolinkingModuleResolutionEnabled,\n isExporting,\n isNamedRequiresEnabled: env.EXPO_USE_METRO_REQUIRE,\n isReactServerComponentsEnabled: serverComponentsEnabled,\n getMetroBundler,\n });\n\n event('config', {\n serverRoot: event.path(serverRoot),\n projectRoot: event.path(projectRoot),\n exporting: isExporting,\n flags: {\n autolinkingModuleResolution: autolinkingModuleResolutionEnabled,\n serverActions: serverActionsEnabled,\n serverComponents: serverComponentsEnabled,\n reactCompiler: reactCompilerEnabled,\n optimizeGraph: env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH,\n treeshaking: env.EXPO_UNSTABLE_TREE_SHAKING,\n logbox: env.EXPO_UNSTABLE_LOG_BOX,\n },\n });\n\n return {\n config,\n setEventReporter: (logger: (event: any) => void) => (reportEvent = logger),\n reporter: terminalReporter,\n };\n}\n\ninterface InstantiateMetroConfigOptions extends LoadMetroConfigOptions {\n host?: string;\n}\n\n/** The most generic possible setup for Metro bundler. */\nexport async function instantiateMetroAsync(\n metroBundler: MetroBundlerDevServer,\n options: InstantiateMetroConfigOptions,\n {\n isExporting,\n exp = getConfig(metroBundler.projectRoot, {\n skipSDKVersionRequirement: true,\n }).exp,\n }: { isExporting: boolean; exp?: ExpoConfig }\n): Promise<{\n metro: MetroServer;\n hmrServer: MetroHmrServer<MetroHmrClient> | null;\n server: http.Server;\n address: ServerAddressInfo | null;\n middleware: any;\n messageSocket: MessageSocket;\n}> {\n const projectRoot = metroBundler.projectRoot;\n const getMetroBundler = () => metro.getBundler().getBundler();\n\n const {\n config: metroConfig,\n setEventReporter,\n reporter,\n } = await loadMetroConfigAsync(projectRoot, options, {\n exp,\n isExporting,\n getMetroBundler,\n });\n\n // Get local URL to Metro bundler server (typically configured as 127.0.0.1:8081)\n const serverBaseUrl = metroBundler\n .getUrlCreator()\n .constructUrl({ scheme: 'http', hostType: 'localhost' });\n\n // Create the core middleware stack for Metro, including websocket listeners\n const { middleware, messagesSocket, eventsSocket, websocketEndpoints } = createMetroMiddleware(\n metroConfig,\n { getMetroBundler, serverBaseUrl }\n );\n\n if (!isExporting) {\n // Enable correct CORS headers for Expo Router features\n prependMiddleware(middleware, createCorsMiddleware(exp));\n\n // Enable debug middleware for CDP-related debugging\n const { debugMiddleware, debugWebsocketEndpoints } = createDebugMiddleware({\n serverBaseUrl,\n reporter,\n });\n Object.assign(websocketEndpoints, debugWebsocketEndpoints);\n middleware.use(debugMiddleware);\n middleware.use('/_expo/debugger', createJsInspectorMiddleware({ serverBaseUrl }));\n\n // TODO(cedric): `enhanceMiddleware` is deprecated, but is currently used to unify the middleware stacks\n // See: https://github.com/facebook/metro/commit/22e85fde85ec454792a1b70eba4253747a2587a9\n // See: https://github.com/facebook/metro/commit/d0d554381f119bb80ab09dbd6a1d310b54737e52\n const customEnhanceMiddleware = metroConfig.server.enhanceMiddleware;\n asWritable(metroConfig.server).enhanceMiddleware = (\n metroMiddleware: any,\n server: MetroServer\n ) => {\n if (customEnhanceMiddleware) {\n metroMiddleware = customEnhanceMiddleware(metroMiddleware, server);\n }\n return middleware.use(metroMiddleware);\n };\n\n const devtoolsWebsocketEndpoints = createDevToolsPluginWebsocketEndpoint();\n Object.assign(websocketEndpoints, devtoolsWebsocketEndpoints);\n }\n\n // Attach Expo Atlas if enabled\n await attachAtlasAsync({\n isExporting,\n exp,\n projectRoot,\n middleware,\n metroConfig,\n // NOTE(cedric): reset the Atlas file once, and reuse it for static exports\n resetAtlasFile: isExporting,\n });\n\n // Support HTTPS based on the metro's tls server config\n // TODO(@kitten): Remove cast once `@expo/metro` is updated to a Metro version that supports the tls config\n const tls = (metroConfig.server as typeof metroConfig.server & { tls?: SecureServerOptions })\n ?.tls;\n const secureServerOptions = tls\n ? {\n key: tls.key,\n cert: tls.cert,\n ca: tls.ca,\n requestCert: tls.requestCert,\n }\n : undefined;\n\n const watch = !isExporting && isWatchEnabled();\n\n const { address, server, hmrServer, metro } = await replaceMetroFileMap(() => {\n return runServer(\n metroBundler,\n metroConfig,\n {\n host: options.host,\n websocketEndpoints,\n watch,\n secureServerOptions,\n },\n {\n mockServer: isExporting,\n }\n );\n });\n\n event('instantiate', {\n atlas: env.EXPO_ATLAS,\n workers: metroConfig.maxWorkers ?? null,\n host: address?.address ?? null,\n port: address?.port ?? null,\n });\n\n // Patch transform file to remove inconvenient customTransformOptions which are only used in single well-known files.\n const originalTransformFile = metro\n .getBundler()\n .getBundler()\n .transformFile.bind(metro.getBundler().getBundler());\n\n metro.getBundler().getBundler().transformFile = async function (\n filePath: string,\n transformOptions: TransformOptions,\n fileBuffer?: Buffer\n ) {\n return originalTransformFile(\n filePath,\n pruneCustomTransformOptions(\n projectRoot,\n filePath,\n // Clone the options so we don't mutate the original.\n {\n ...transformOptions,\n customTransformOptions: {\n __proto__: null,\n ...transformOptions.customTransformOptions,\n },\n }\n ),\n fileBuffer\n );\n };\n\n // Layered on top of the prune patch above. Both fresh worker results\n // and cache hits flow through `Bundler.transformFile`, so wrapping\n // here covers both.\n patchTransformFileForPackedMaps(metro.getBundler().getBundler());\n patchMetroSourceMapStringForPackedMaps();\n\n setEventReporter(eventsSocket.reportMetroEvent);\n\n // This function ensures that modules in source maps are sorted in the same\n // order as in a plain JS bundle.\n metro._getSortedModules = function (this: MetroServerWithModuleIdMod, graph: ReadOnlyGraph) {\n const modules = [...graph.dependencies.values()];\n\n const ctx = {\n // TODO(@kitten): Increase type-safety here\n platform: graph.transformOptions.platform!,\n environment: graph.transformOptions.customTransformOptions?.environment,\n };\n // Assign IDs to modules in a consistent order\n for (const module of modules) {\n this._createModuleId(module.path, ctx);\n }\n // Sort by IDs\n return modules.sort(\n (a, b) => this._createModuleId(a.path, ctx) - this._createModuleId(b.path, ctx)\n );\n };\n\n if (hmrServer) {\n let hmrJSBundle:\n | typeof import('@expo/metro-config/build/serializer/fork/hmrJSBundle').default\n | typeof import('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle').default;\n\n try {\n hmrJSBundle = require('@expo/metro-config/build/serializer/fork/hmrJSBundle').default;\n } catch {\n // TODO: Add fallback for monorepo tests up until the fork is merged.\n Log.warn('Failed to load HMR serializer from @expo/metro-config, using fallback version.');\n hmrJSBundle = require('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle');\n }\n\n // Patch HMR Server to send more info to the `_createModuleId` function for deterministic module IDs and add support for serializing HMR updates the same as all other bundles.\n hmrServer._prepareMessage = async function (\n this: MetroHmrServerWithModuleIdMod,\n group,\n options,\n changeEvent\n ) {\n // Fork of https://github.com/facebook/metro/blob/3b3e0aaf725cfa6907bf2c8b5fbc0da352d29efe/packages/metro/src/HmrServer.js#L327-L393\n // with patch for `_createModuleId`.\n const logger = !options.isInitialUpdate ? changeEvent?.logger : null;\n try {\n const revPromise = this._bundler.getRevision(group.revisionId);\n if (!revPromise) {\n return {\n type: 'error',\n body: formatBundlingError(new RevisionNotFoundError(group.revisionId)),\n };\n }\n logger?.point('updateGraph_start');\n const { revision, delta } = await this._bundler.updateGraph(await revPromise, false);\n logger?.point('updateGraph_end');\n this._clientGroups.delete(group.revisionId);\n group.revisionId = revision.id;\n for (const client of group.clients) {\n client.revisionIds = client.revisionIds.filter(\n (revisionId) => revisionId !== group.revisionId\n );\n client.revisionIds.push(revision.id);\n }\n this._clientGroups.set(group.revisionId, group);\n logger?.point('serialize_start');\n // NOTE(EvanBacon): This is the patch\n const moduleIdContext = {\n // TODO(@kitten): Increase type-safety here\n platform: revision.graph.transformOptions.platform!,\n environment: revision.graph.transformOptions.customTransformOptions?.environment,\n };\n const hmrUpdate = hmrJSBundle(delta, revision.graph, {\n clientUrl: group.clientUrl,\n // NOTE(EvanBacon): This is also the patch\n createModuleId: (moduleId: string) => {\n return this._createModuleId(moduleId, moduleIdContext);\n },\n includeAsyncPaths: group.graphOptions.lazy,\n projectRoot: this._config.projectRoot,\n serverRoot: this._config.server.unstable_serverRoot ?? this._config.projectRoot,\n });\n logger?.point('serialize_end');\n return {\n type: 'update',\n body: {\n revisionId: revision.id,\n isInitialUpdate: options.isInitialUpdate,\n ...hmrUpdate,\n },\n };\n } catch (error: any) {\n const formattedError = formatBundlingError(error);\n this._config.reporter.update({\n type: 'bundling_error',\n error,\n });\n return {\n type: 'error',\n body: formattedError,\n };\n }\n };\n }\n\n return {\n metro,\n hmrServer,\n server,\n middleware,\n messageSocket: messagesSocket,\n address,\n };\n}\n\n// TODO: Fork the entire transform function so we can simply regex the file contents for keywords instead.\nfunction pruneCustomTransformOptions(\n projectRoot: string,\n filePath: string,\n transformOptions: TransformOptions\n): TransformOptions {\n // Normalize the filepath for cross platform checking.\n filePath = filePath.split(path.sep).join('/');\n\n if (\n transformOptions.customTransformOptions?.dom &&\n // The only generated file that needs the dom root is `expo/dom/entry.js`\n !filePath.match(/expo\\/dom\\/entry\\.js$/)\n ) {\n // Clear the dom root option if we aren't transforming the magic entry file, this ensures\n // that cached artifacts from other DOM component bundles can be reused.\n transformOptions.customTransformOptions.dom = 'true';\n }\n\n const routerRoot = transformOptions.customTransformOptions?.routerRoot;\n if (typeof routerRoot === 'string') {\n const isRouterEntry = /\\/expo-router\\/_ctx/.test(filePath);\n // The router root is used all over expo-router (`process.env.EXPO_ROUTER_ABS_APP_ROOT`, `process.env.EXPO_ROUTER_APP_ROOT`) so we'll just ignore the entire package.\n const isRouterModule = /\\/expo-router\\/build\\//.test(filePath);\n // Any page/router inside the expo-router app folder may access the `routerRoot` option to determine whether it's in the app folder\n const resolvedRouterRoot = path.resolve(projectRoot, routerRoot).split(path.sep).join('/');\n const isRouterRoute = path.isAbsolute(filePath) && filePath.startsWith(resolvedRouterRoot);\n\n // In any other file than the above, we enforce that we mustn't use `routerRoot`, and set it to an arbitrary value here (the default)\n // to ensure that the cache never invalidates when this value is changed\n if (!isRouterEntry && !isRouterModule && !isRouterRoute) {\n transformOptions.customTransformOptions!.routerRoot = 'app';\n }\n }\n\n if (\n transformOptions.customTransformOptions?.asyncRoutes &&\n // The async routes settings are also used in `expo-router/_ctx.ios.js` (and other platform variants) via `process.env.EXPO_ROUTER_IMPORT_MODE`\n !(filePath.match(/\\/expo-router\\/_ctx/) || filePath.match(/\\/expo-router\\/build\\//))\n ) {\n delete transformOptions.customTransformOptions.asyncRoutes;\n }\n\n if (\n transformOptions.customTransformOptions?.clientBoundaries &&\n // The client boundaries are only used in `expo/virtual/rsc.js` for production RSC exports.\n !filePath.match(/\\/expo\\/virtual\\/rsc\\.js$/)\n ) {\n delete transformOptions.customTransformOptions.clientBoundaries;\n }\n\n return transformOptions;\n}\n\n/**\n * Simplify and communicate if Metro is running without watching file updates,.\n * Exposed for testing.\n */\nexport function isWatchEnabled() {\n if (env.CI) {\n Log.log(\n chalk`Metro is running in CI mode, reloads are disabled. Remove {bold CI=true} to enable watch mode.`\n );\n }\n\n return !env.CI;\n}\n"],"names":["event","instantiateMetroAsync","isWatchEnabled","loadMetroConfigAsync","events","t","asWritable","input","LogRespectingTerminal","Terminal","stream","ttyPrint","sendLog","msg","length","log","format","args","flush","sendStderr","logStderr","require","console","info","warn","error","process","on","status","lines","splice","stderr","write","join","line","stdout","isTTY","push","prev","terminal","projectRoot","options","exp","isExporting","getMetroBundler","config","reportEvent","serverRoot","getMetroServerRoot","isWorkspace","autolinkingModuleResolutionEnabled","experiments","autolinkingModuleResolution","serverActionsEnabled","reactServerFunctions","env","EXPO_UNSTABLE_SERVER_FUNCTIONS","serverComponentsEnabled","reactServerComponentRoutes","EXPO_USE_METRO_REQUIRE","reactCanary","Log","terminalReporter","MetroTerminalReporter","loadUserConfig","overrideConfigPath","EXPO_OVERRIDE_METRO_CONFIG","undefined","resetCache","maxWorkers","server","port","reporter","update","onDemandFilesystem","resolver","unstable_onDemandFilesystem","globalThis","__requireCycleIgnorePatterns","requireCycleIgnorePatterns","transformer","publicPath","baseUrl","platformBundlers","getPlatformBundlers","reduceLogs","shouldReduceLogs","reactCompilerEnabled","reactCompiler","chalk","gray","EXPO_UNSTABLE_TREE_SHAKING","EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH","CommandError","EXPO_UNSTABLE_LOG_BOX","withMetroMultiPlatformAsync","isTsconfigPathsEnabled","tsconfigPaths","isAutolinkingResolverEnabled","isNamedRequiresEnabled","isReactServerComponentsEnabled","path","exporting","flags","serverActions","serverComponents","optimizeGraph","treeshaking","logbox","setEventReporter","logger","metroBundler","getConfig","skipSDKVersionRequirement","metroConfig","metro","getBundler","serverBaseUrl","getUrlCreator","constructUrl","scheme","hostType","middleware","messagesSocket","eventsSocket","websocketEndpoints","createMetroMiddleware","prependMiddleware","createCorsMiddleware","debugMiddleware","debugWebsocketEndpoints","createDebugMiddleware","Object","assign","use","createJsInspectorMiddleware","customEnhanceMiddleware","enhanceMiddleware","metroMiddleware","devtoolsWebsocketEndpoints","createDevToolsPluginWebsocketEndpoint","attachAtlasAsync","resetAtlasFile","tls","secureServerOptions","key","cert","ca","requestCert","watch","address","hmrServer","replaceMetroFileMap","runServer","host","mockServer","atlas","EXPO_ATLAS","workers","originalTransformFile","transformFile","bind","filePath","transformOptions","fileBuffer","pruneCustomTransformOptions","customTransformOptions","__proto__","patchTransformFileForPackedMaps","patchMetroSourceMapStringForPackedMaps","reportMetroEvent","_getSortedModules","graph","modules","dependencies","values","ctx","platform","environment","module","_createModuleId","sort","a","b","hmrJSBundle","default","_prepareMessage","group","changeEvent","isInitialUpdate","revision","revPromise","_bundler","getRevision","revisionId","type","body","formatBundlingError","RevisionNotFoundError","point","delta","updateGraph","_clientGroups","delete","id","client","clients","revisionIds","filter","set","moduleIdContext","hmrUpdate","clientUrl","createModuleId","moduleId","includeAsyncPaths","graphOptions","lazy","_config","unstable_serverRoot","formattedError","messageSocket","split","sep","dom","match","routerRoot","isRouterEntry","test","isRouterModule","resolvedRouterRoot","resolve","isRouterRoute","isAbsolute","startsWith","asyncRoutes","clientBoundaries","CI"],"mappings":";;;;;;;;;;;QAuCaA;eAAAA;;QAySSC;eAAAA;;QAyUNC;eAAAA;;QAreMC;eAAAA;;;;yBApLqB;;;;;;;yBACR;;;;;;;gEAOD;;;;;;;gEAEF;;;;;;;yBACP;;;;;;;yBAEM;;;;;;;yBACiB;;;;;;;yBACO;;;;;;;gEACrC;;;;;;;gEAED;;;;;;iDAEqC;uCAEhB;mCACF;6BACH;uCACK;uCACA;+BACsC;wCAChC;wBACH;qBACrB;qBACA;wBACS;gCACQ;6CACO;2BACV;kCACE;;;;;;AAG7B,MAAMH,QAAQI,IAAAA,cAAM,EAAC,SAAS,CAACC,IAAM;QAC1CA,EAAEL,KAAK;QA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,iBAAiB,CAACE,kBAAkB,CAACG,eAAe;YACvDrE,iBAAiBG,sBAAsB,CAAE4D,UAAU,GAAG;QACxD;IACF;IAEA,IACE/D,EAAAA,4CAAAA,iBAAiBG,sBAAsB,qBAAvCH,0CAAyCwE,WAAW,KACpD,+IAA+I;IAC/I,CAAEzE,CAAAA,SAAS+D,KAAK,CAAC,0BAA0B/D,SAAS+D,KAAK,CAAC,yBAAwB,GAClF;QACA,OAAO9D,iBAAiBG,sBAAsB,CAACqE,WAAW;IAC5D;IAEA,IACExE,EAAAA,4CAAAA,iBAAiBG,sBAAsB,qBAAvCH,0CAAyCyE,gBAAgB,KACzD,2FAA2F;IAC3F,CAAC1E,SAAS+D,KAAK,CAAC,8BAChB;QACA,OAAO9D,iBAAiBG,sBAAsB,CAACsE,gBAAgB;IACjE;IAEA,OAAOzE;AACT;AAMO,SAASjK;IACd,IAAIqD,QAAG,CAACsL,EAAE,EAAE;QACVhL,QAAG,CAAC9C,GAAG,CACL0E,IAAAA,gBAAK,CAAA,CAAC,8FAA8F,CAAC;IAEzG;IAEA,OAAO,CAAClC,QAAG,CAACsL,EAAE;AAChB"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/instantiateMetro.ts"],"sourcesContent":["import { type ExpoConfig, getConfig, getPlatformsFromConfig } from '@expo/config';\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport type { Reporter } from '@expo/metro/metro';\nimport type Bundler from '@expo/metro/metro/Bundler';\nimport type { ReadOnlyGraph } from '@expo/metro/metro/DeltaBundler';\nimport type { TransformOptions } from '@expo/metro/metro/DeltaBundler/Worker';\nimport type { Client as MetroHmrClient } from '@expo/metro/metro/HmrServer';\nimport type MetroHmrServer from '@expo/metro/metro/HmrServer';\nimport RevisionNotFoundError from '@expo/metro/metro/IncrementalBundler/RevisionNotFoundError';\nimport type MetroServer from '@expo/metro/metro/Server';\nimport formatBundlingError from '@expo/metro/metro/lib/formatBundlingError';\nimport { Terminal } from '@expo/metro/metro-core';\nimport type { createStableModuleIdFactory } from '@expo/metro-config';\nimport { loadUserConfig } from '@expo/metro-config';\nimport { patchTransformFileForPackedMaps } from '@expo/metro-config/build/serializer/packedMap';\nimport { patchMetroSourceMapStringForPackedMaps } from '@expo/metro-config/build/serializer/sourceMap';\nimport chalk from 'chalk';\nimport type http from 'http';\nimport path from 'path';\n\nimport { createDevToolsPluginWebsocketEndpoint } from './DevToolsPluginWebsocketEndpoint';\nimport type { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { MetroTerminalReporter } from './MetroTerminalReporter';\nimport { replaceMetroFileMap } from './createFileMap-fork';\nimport { attachAtlasAsync } from './debugging/attachAtlas';\nimport { createDebugMiddleware } from './debugging/createDebugMiddleware';\nimport { createMetroMiddleware } from './dev-server/createMetroMiddleware';\nimport { runServer, type ServerAddressInfo, type SecureServerOptions } from './runServer-fork';\nimport { withMetroMultiPlatformAsync } from './withMetroMultiPlatform';\nimport { events, shouldReduceLogs } from '../../../events';\nimport { Log } from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { createCorsMiddleware } from '../middleware/CorsMiddleware';\nimport { createJsInspectorMiddleware } from '../middleware/inspector/createJsInspectorMiddleware';\nimport { prependMiddleware } from '../middleware/mutations';\nimport { getPlatformBundlers } from '../platformBundlers';\n\n// prettier-ignore\nexport const event = events('metro', (t) => [\n t.event<'config', {\n serverRoot: string;\n projectRoot: string;\n exporting: boolean;\n flags: {\n autolinkingModuleResolution: boolean;\n serverActions: boolean;\n serverComponents: boolean;\n reactCompiler: boolean;\n optimizeGraph?: boolean;\n treeshaking?: boolean;\n logbox?: boolean;\n };\n }>(),\n t.event<'instantiate', {\n atlas: boolean;\n workers: number | null;\n host: string | null;\n port: number | null;\n }>(),\n]);\n\n// NOTE(@kitten): We pass a custom createStableModuleIdFactory function into the Metro module ID factory sometimes\ninterface MetroServerWithModuleIdMod extends MetroServer {\n _createModuleId: ReturnType<typeof createStableModuleIdFactory> & ((path: string) => number);\n}\ninterface MetroHmrServerWithModuleIdMod extends MetroHmrServer<MetroHmrClient> {\n _createModuleId: ReturnType<typeof createStableModuleIdFactory> & ((path: string) => number);\n}\n\n// From expo/dev-server but with ability to use custom logger.\ntype MessageSocket = {\n broadcast: (method: string, params?: Record<string, any> | undefined) => void;\n};\n\n// TODO(@kitten): We assign this here to run server-side code bundled by metro\n// It's not isolated into a worker thread yet\n// Check `metro-require/require.ts` for how this setting is used\ndeclare namespace globalThis {\n let __requireCycleIgnorePatterns: readonly RegExp[] | undefined;\n}\n\nfunction asWritable<T>(input: T): { -readonly [K in keyof T]: T[K] } {\n return input;\n}\n\n/**\n * Extends Metro's Terminal to intercept all console methods so they don't\n * corrupt the progress bar status lines.\n *\n * console.log/info are routed through terminal.log() (stdout, managed).\n * console.warn/error are routed through logStderr() which clears the\n * status from stdout before writing to stderr, then restores it.\n * Without this, unmanaged stderr writes shift the cursor and cause\n * progress bars to get stuck as permanent output.\n */\nclass LogRespectingTerminal extends Terminal {\n #stderrQueue: string[] = [];\n #drainingStderr = false;\n\n constructor(stream: import('node:net').Socket | import('node:stream').Writable) {\n super(stream, { ttyPrint: true });\n\n const sendLog = (...msg: any[]) => {\n if (!msg.length) {\n this.log('');\n } else {\n const [format, ...args] = msg;\n this.log(format, ...args);\n }\n // Flush the logs to the terminal immediately so logs at the end of the process are not lost.\n this.flush();\n };\n\n const sendStderr = (...msg: any[]) => {\n if (!msg.length) {\n this.logStderr('');\n } else {\n const [format, ...args] = msg;\n this.logStderr(require('util').format(format, ...args));\n }\n };\n\n console.log = sendLog;\n console.info = sendLog;\n console.warn = sendStderr;\n console.error = sendStderr;\n\n // NOTE(@kitten): We flush the stderr queue immediately when we're about to exit\n process.on('exit', () => {\n if (!this.#drainingStderr && this.#stderrQueue.length) {\n this.#drainingStderr = true;\n this.status('');\n const lines = this.#stderrQueue.splice(0);\n process.stderr.write(lines.join('\\n') + '\\n');\n }\n });\n }\n\n /** Write to stderr without corrupting Terminal's cursor tracking. */\n logStderr(line: string): void {\n if (!(process.stdout as any).isTTY) {\n process.stderr.write(line + '\\n');\n return;\n }\n this.#stderrQueue.push(line);\n this.#drainStderr();\n }\n\n async #drainStderr(): Promise<void> {\n if (this.#drainingStderr) return;\n this.#drainingStderr = true;\n\n while (this.#stderrQueue.length > 0) {\n // Clear status, flush to ensure it's removed from screen\n const prev = this.status('');\n await this.flush();\n\n // Write to stderr while status is cleared\n const lines = this.#stderrQueue.splice(0);\n process.stderr.write(lines.join('\\n') + '\\n');\n\n // Restore status\n this.status(prev);\n }\n\n this.#drainingStderr = false;\n }\n}\n\n// Share one instance of Terminal for all instances of Metro.\nconst terminal = new LogRespectingTerminal(process.stdout);\n\ninterface LoadMetroConfigOptions {\n maxWorkers?: number;\n port?: number;\n reporter?: Reporter;\n resetCache?: boolean;\n}\n\nexport async function loadMetroConfigAsync(\n projectRoot: string,\n options: LoadMetroConfigOptions,\n {\n exp,\n isExporting,\n getMetroBundler,\n }: { exp: ExpoConfig; isExporting: boolean; getMetroBundler: () => Bundler }\n) {\n let reportEvent: ((event: any) => void) | undefined;\n\n // We're resolving a monorepo root, higher up than the `projectRoot`. If this\n // folder is different (presumably a parent) we're in a monorepo\n const serverRoot = getMetroServerRoot(projectRoot);\n const isWorkspace = serverRoot !== projectRoot;\n\n // Out-of-tree platforms (tvos/macos) rely on the autolinking module resolver to remap the\n // react-native package to their support package, and require autolinking module resolution\n const targetsOutOfTreePlatform = getPlatformsFromConfig(projectRoot, exp).some(\n (platform) => platform === 'tvos' || platform === 'macos'\n );\n\n // Autolinking Module Resolution is enabled by default in a monorepo or for out-of-tree platforms.\n const autolinkingModuleResolutionEnabled =\n exp.experiments?.autolinkingModuleResolution ?? (isWorkspace || targetsOutOfTreePlatform);\n\n const serverActionsEnabled =\n exp.experiments?.reactServerFunctions ?? env.EXPO_UNSTABLE_SERVER_FUNCTIONS;\n const serverComponentsEnabled = !!exp.experiments?.reactServerComponentRoutes;\n if (serverActionsEnabled) {\n process.env.EXPO_UNSTABLE_SERVER_FUNCTIONS = '1';\n }\n\n // NOTE: Enable all the experimental Metro flags when RSC is enabled.\n if (serverComponentsEnabled || serverActionsEnabled) {\n process.env.EXPO_USE_METRO_REQUIRE = '1';\n }\n\n if (exp.experiments?.reactCanary) {\n Log.warn(`React 19 is enabled by default. Remove unused experiments.reactCanary flag.`);\n }\n\n const terminalReporter = new MetroTerminalReporter(serverRoot, terminal);\n\n let config = await loadUserConfig({\n projectRoot,\n serverRoot,\n // NOTE: Allow external tools to override the metro config. This is considered internal and unstable\n overrideConfigPath: env.EXPO_OVERRIDE_METRO_CONFIG ?? undefined,\n });\n\n config = {\n ...config,\n // See: `overrideConfigWithArguments` https://github.com/facebook/metro/blob/5059e26/packages/metro-config/src/loadConfig.js#L274-L339\n // Compare to `LoadOptions` type (disregard `reporter` as we don't expose this)\n resetCache: !!options.resetCache,\n maxWorkers: options.maxWorkers ?? config.maxWorkers,\n server: {\n ...config.server,\n port: options.port ?? config.server.port,\n },\n // Force-override the reporter\n reporter: {\n update(event) {\n terminalReporter.update(event);\n if (reportEvent) {\n reportEvent(event);\n }\n },\n },\n };\n\n // On-Demand Filesystem is enabled by default\n // TODO(@kitten): Add to config-types JSON schema\n const onDemandFilesystem = exp.experiments?.onDemandFilesystem ?? true;\n asWritable(config.resolver).unstable_onDemandFilesystem = onDemandFilesystem;\n\n globalThis.__requireCycleIgnorePatterns = config.resolver?.requireCycleIgnorePatterns;\n\n if (isExporting) {\n // This token will be used in the asset plugin to ensure the path is correct for writing locally.\n asWritable(config.transformer).publicPath = `/assets?export_path=${\n (exp.experiments?.baseUrl ?? '') + '/assets'\n }`;\n } else {\n asWritable(config.transformer).publicPath = '/assets/?unstable_path=.';\n }\n\n const platformBundlers = getPlatformBundlers(projectRoot, exp);\n const reduceLogs = shouldReduceLogs();\n\n const reactCompilerEnabled = !!exp.experiments?.reactCompiler;\n if (!reduceLogs && reactCompilerEnabled) {\n Log.log(chalk.gray`React Compiler enabled`);\n }\n\n if (!reduceLogs && autolinkingModuleResolutionEnabled) {\n Log.log(chalk.gray`Expo Autolinking module resolution enabled`);\n }\n\n if (env.EXPO_UNSTABLE_TREE_SHAKING && !env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n throw new CommandError(\n 'EXPO_UNSTABLE_TREE_SHAKING requires EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH to be enabled.'\n );\n }\n\n if (!reduceLogs && env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n Log.warn(`Experimental bundle optimization is enabled.`);\n }\n if (!reduceLogs && env.EXPO_UNSTABLE_TREE_SHAKING) {\n Log.warn(`Experimental tree shaking is enabled.`);\n }\n if (!reduceLogs && env.EXPO_UNSTABLE_LOG_BOX) {\n Log.warn(`Experimental Expo LogBox is enabled.`);\n }\n\n if (!reduceLogs && serverActionsEnabled) {\n Log.warn(\n `React Server Functions (beta) are enabled. Route rendering mode: ${exp.experiments?.reactServerComponentRoutes ? 'server' : 'client'}`\n );\n }\n\n config = await withMetroMultiPlatformAsync(projectRoot, {\n config,\n exp,\n platformBundlers,\n serverRoot,\n isTsconfigPathsEnabled: exp.experiments?.tsconfigPaths ?? true,\n isAutolinkingResolverEnabled: autolinkingModuleResolutionEnabled,\n isExporting,\n isNamedRequiresEnabled: env.EXPO_USE_METRO_REQUIRE,\n isReactServerComponentsEnabled: serverComponentsEnabled,\n getMetroBundler,\n });\n\n event('config', {\n serverRoot: event.path(serverRoot),\n projectRoot: event.path(projectRoot),\n exporting: isExporting,\n flags: {\n autolinkingModuleResolution: autolinkingModuleResolutionEnabled,\n serverActions: serverActionsEnabled,\n serverComponents: serverComponentsEnabled,\n reactCompiler: reactCompilerEnabled,\n optimizeGraph: env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH,\n treeshaking: env.EXPO_UNSTABLE_TREE_SHAKING,\n logbox: env.EXPO_UNSTABLE_LOG_BOX,\n },\n });\n\n return {\n config,\n setEventReporter: (logger: (event: any) => void) => (reportEvent = logger),\n reporter: terminalReporter,\n };\n}\n\ninterface InstantiateMetroConfigOptions extends LoadMetroConfigOptions {\n host?: string;\n}\n\n/** The most generic possible setup for Metro bundler. */\nexport async function instantiateMetroAsync(\n metroBundler: MetroBundlerDevServer,\n options: InstantiateMetroConfigOptions,\n {\n isExporting,\n exp = getConfig(metroBundler.projectRoot, {\n skipSDKVersionRequirement: true,\n }).exp,\n }: { isExporting: boolean; exp?: ExpoConfig }\n): Promise<{\n metro: MetroServer;\n hmrServer: MetroHmrServer<MetroHmrClient> | null;\n server: http.Server;\n address: ServerAddressInfo | null;\n middleware: any;\n messageSocket: MessageSocket;\n}> {\n const projectRoot = metroBundler.projectRoot;\n const getMetroBundler = () => metro.getBundler().getBundler();\n\n const {\n config: metroConfig,\n setEventReporter,\n reporter,\n } = await loadMetroConfigAsync(projectRoot, options, {\n exp,\n isExporting,\n getMetroBundler,\n });\n\n // Get local URL to Metro bundler server (typically configured as 127.0.0.1:8081)\n const serverBaseUrl = metroBundler\n .getUrlCreator()\n .constructUrl({ scheme: 'http', hostType: 'localhost' });\n\n // Create the core middleware stack for Metro, including websocket listeners\n const { middleware, messagesSocket, eventsSocket, websocketEndpoints } = createMetroMiddleware(\n metroConfig,\n { getMetroBundler, serverBaseUrl }\n );\n\n if (!isExporting) {\n // Enable correct CORS headers for Expo Router features\n prependMiddleware(middleware, createCorsMiddleware(exp));\n\n // Enable debug middleware for CDP-related debugging\n const { debugMiddleware, debugWebsocketEndpoints } = createDebugMiddleware({\n serverBaseUrl,\n reporter,\n });\n Object.assign(websocketEndpoints, debugWebsocketEndpoints);\n middleware.use(debugMiddleware);\n middleware.use('/_expo/debugger', createJsInspectorMiddleware({ serverBaseUrl }));\n\n // TODO(cedric): `enhanceMiddleware` is deprecated, but is currently used to unify the middleware stacks\n // See: https://github.com/facebook/metro/commit/22e85fde85ec454792a1b70eba4253747a2587a9\n // See: https://github.com/facebook/metro/commit/d0d554381f119bb80ab09dbd6a1d310b54737e52\n const customEnhanceMiddleware = metroConfig.server.enhanceMiddleware;\n asWritable(metroConfig.server).enhanceMiddleware = (\n metroMiddleware: any,\n server: MetroServer\n ) => {\n if (customEnhanceMiddleware) {\n metroMiddleware = customEnhanceMiddleware(metroMiddleware, server);\n }\n return middleware.use(metroMiddleware);\n };\n\n const devtoolsWebsocketEndpoints = createDevToolsPluginWebsocketEndpoint();\n Object.assign(websocketEndpoints, devtoolsWebsocketEndpoints);\n }\n\n // Attach Expo Atlas if enabled\n await attachAtlasAsync({\n isExporting,\n exp,\n projectRoot,\n middleware,\n metroConfig,\n // NOTE(cedric): reset the Atlas file once, and reuse it for static exports\n resetAtlasFile: isExporting,\n });\n\n // Support HTTPS based on the metro's tls server config\n // TODO(@kitten): Remove cast once `@expo/metro` is updated to a Metro version that supports the tls config\n const tls = (metroConfig.server as typeof metroConfig.server & { tls?: SecureServerOptions })\n ?.tls;\n const secureServerOptions = tls\n ? {\n key: tls.key,\n cert: tls.cert,\n ca: tls.ca,\n requestCert: tls.requestCert,\n }\n : undefined;\n\n const watch = !isExporting && isWatchEnabled();\n\n const { address, server, hmrServer, metro } = await replaceMetroFileMap(() => {\n return runServer(\n metroBundler,\n metroConfig,\n {\n host: options.host,\n websocketEndpoints,\n watch,\n secureServerOptions,\n },\n {\n mockServer: isExporting,\n }\n );\n });\n\n event('instantiate', {\n atlas: env.EXPO_ATLAS,\n workers: metroConfig.maxWorkers ?? null,\n host: address?.address ?? null,\n port: address?.port ?? null,\n });\n\n // Patch transform file to remove inconvenient customTransformOptions which are only used in single well-known files.\n const originalTransformFile = metro\n .getBundler()\n .getBundler()\n .transformFile.bind(metro.getBundler().getBundler());\n\n metro.getBundler().getBundler().transformFile = async function (\n filePath: string,\n transformOptions: TransformOptions,\n fileBuffer?: Buffer\n ) {\n return originalTransformFile(\n filePath,\n pruneCustomTransformOptions(\n projectRoot,\n filePath,\n // Clone the options so we don't mutate the original.\n {\n ...transformOptions,\n customTransformOptions: {\n __proto__: null,\n ...transformOptions.customTransformOptions,\n },\n }\n ),\n fileBuffer\n );\n };\n\n // Layered on top of the prune patch above. Both fresh worker results\n // and cache hits flow through `Bundler.transformFile`, so wrapping\n // here covers both.\n patchTransformFileForPackedMaps(metro.getBundler().getBundler());\n patchMetroSourceMapStringForPackedMaps();\n\n setEventReporter(eventsSocket.reportMetroEvent);\n\n // This function ensures that modules in source maps are sorted in the same\n // order as in a plain JS bundle.\n metro._getSortedModules = function (this: MetroServerWithModuleIdMod, graph: ReadOnlyGraph) {\n const modules = [...graph.dependencies.values()];\n\n const ctx = {\n // TODO(@kitten): Increase type-safety here\n platform: graph.transformOptions.platform!,\n environment: graph.transformOptions.customTransformOptions?.environment,\n };\n // Assign IDs to modules in a consistent order\n for (const module of modules) {\n this._createModuleId(module.path, ctx);\n }\n // Sort by IDs\n return modules.sort(\n (a, b) => this._createModuleId(a.path, ctx) - this._createModuleId(b.path, ctx)\n );\n };\n\n if (hmrServer) {\n let hmrJSBundle:\n | typeof import('@expo/metro-config/build/serializer/fork/hmrJSBundle').default\n | typeof import('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle').default;\n\n try {\n hmrJSBundle = require('@expo/metro-config/build/serializer/fork/hmrJSBundle').default;\n } catch {\n // TODO: Add fallback for monorepo tests up until the fork is merged.\n Log.warn('Failed to load HMR serializer from @expo/metro-config, using fallback version.');\n hmrJSBundle = require('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle');\n }\n\n // Patch HMR Server to send more info to the `_createModuleId` function for deterministic module IDs and add support for serializing HMR updates the same as all other bundles.\n hmrServer._prepareMessage = async function (\n this: MetroHmrServerWithModuleIdMod,\n group,\n options,\n changeEvent\n ) {\n // Fork of https://github.com/facebook/metro/blob/3b3e0aaf725cfa6907bf2c8b5fbc0da352d29efe/packages/metro/src/HmrServer.js#L327-L393\n // with patch for `_createModuleId`.\n const logger = !options.isInitialUpdate ? changeEvent?.logger : null;\n try {\n const revPromise = this._bundler.getRevision(group.revisionId);\n if (!revPromise) {\n return {\n type: 'error',\n body: formatBundlingError(new RevisionNotFoundError(group.revisionId)),\n };\n }\n logger?.point('updateGraph_start');\n const { revision, delta } = await this._bundler.updateGraph(await revPromise, false);\n logger?.point('updateGraph_end');\n this._clientGroups.delete(group.revisionId);\n group.revisionId = revision.id;\n for (const client of group.clients) {\n client.revisionIds = client.revisionIds.filter(\n (revisionId) => revisionId !== group.revisionId\n );\n client.revisionIds.push(revision.id);\n }\n this._clientGroups.set(group.revisionId, group);\n logger?.point('serialize_start');\n // NOTE(EvanBacon): This is the patch\n const moduleIdContext = {\n // TODO(@kitten): Increase type-safety here\n platform: revision.graph.transformOptions.platform!,\n environment: revision.graph.transformOptions.customTransformOptions?.environment,\n };\n const hmrUpdate = hmrJSBundle(delta, revision.graph, {\n clientUrl: group.clientUrl,\n // NOTE(EvanBacon): This is also the patch\n createModuleId: (moduleId: string) => {\n return this._createModuleId(moduleId, moduleIdContext);\n },\n includeAsyncPaths: group.graphOptions.lazy,\n projectRoot: this._config.projectRoot,\n serverRoot: this._config.server.unstable_serverRoot ?? this._config.projectRoot,\n });\n logger?.point('serialize_end');\n return {\n type: 'update',\n body: {\n revisionId: revision.id,\n isInitialUpdate: options.isInitialUpdate,\n ...hmrUpdate,\n },\n };\n } catch (error: any) {\n const formattedError = formatBundlingError(error);\n this._config.reporter.update({\n type: 'bundling_error',\n error,\n });\n return {\n type: 'error',\n body: formattedError,\n };\n }\n };\n }\n\n return {\n metro,\n hmrServer,\n server,\n middleware,\n messageSocket: messagesSocket,\n address,\n };\n}\n\n// TODO: Fork the entire transform function so we can simply regex the file contents for keywords instead.\nfunction pruneCustomTransformOptions(\n projectRoot: string,\n filePath: string,\n transformOptions: TransformOptions\n): TransformOptions {\n // Normalize the filepath for cross platform checking.\n filePath = filePath.split(path.sep).join('/');\n\n if (\n transformOptions.customTransformOptions?.dom &&\n // The only generated file that needs the dom root is `expo/dom/entry.js`\n !filePath.match(/expo\\/dom\\/entry\\.js$/)\n ) {\n // Clear the dom root option if we aren't transforming the magic entry file, this ensures\n // that cached artifacts from other DOM component bundles can be reused.\n transformOptions.customTransformOptions.dom = 'true';\n }\n\n const routerRoot = transformOptions.customTransformOptions?.routerRoot;\n if (typeof routerRoot === 'string') {\n const isRouterEntry = /\\/expo-router\\/_ctx/.test(filePath);\n // The router root is used all over expo-router (`process.env.EXPO_ROUTER_ABS_APP_ROOT`, `process.env.EXPO_ROUTER_APP_ROOT`) so we'll just ignore the entire package.\n const isRouterModule = /\\/expo-router\\/build\\//.test(filePath);\n // Any page/router inside the expo-router app folder may access the `routerRoot` option to determine whether it's in the app folder\n const resolvedRouterRoot = path.resolve(projectRoot, routerRoot).split(path.sep).join('/');\n const isRouterRoute = path.isAbsolute(filePath) && filePath.startsWith(resolvedRouterRoot);\n\n // In any other file than the above, we enforce that we mustn't use `routerRoot`, and set it to an arbitrary value here (the default)\n // to ensure that the cache never invalidates when this value is changed\n if (!isRouterEntry && !isRouterModule && !isRouterRoute) {\n transformOptions.customTransformOptions!.routerRoot = 'app';\n }\n }\n\n if (\n transformOptions.customTransformOptions?.asyncRoutes &&\n // The async routes settings are also used in `expo-router/_ctx.ios.js` (and other platform variants) via `process.env.EXPO_ROUTER_IMPORT_MODE`\n !(filePath.match(/\\/expo-router\\/_ctx/) || filePath.match(/\\/expo-router\\/build\\//))\n ) {\n delete transformOptions.customTransformOptions.asyncRoutes;\n }\n\n if (\n transformOptions.customTransformOptions?.clientBoundaries &&\n // The client boundaries are only used in `expo/virtual/rsc.js` for production RSC exports.\n !filePath.match(/\\/expo\\/virtual\\/rsc\\.js$/)\n ) {\n delete transformOptions.customTransformOptions.clientBoundaries;\n }\n\n return transformOptions;\n}\n\n/**\n * Simplify and communicate if Metro is running without watching file updates,.\n * Exposed for testing.\n */\nexport function isWatchEnabled() {\n if (env.CI) {\n Log.log(\n chalk`Metro is running in CI mode, reloads are disabled. Remove {bold CI=true} to enable watch mode.`\n );\n }\n\n return !env.CI;\n}\n"],"names":["event","instantiateMetroAsync","isWatchEnabled","loadMetroConfigAsync","events","t","asWritable","input","LogRespectingTerminal","Terminal","stream","ttyPrint","sendLog","msg","length","log","format","args","flush","sendStderr","logStderr","require","console","info","warn","error","process","on","status","lines","splice","stderr","write","join","line","stdout","isTTY","push","prev","terminal","projectRoot","options","exp","isExporting","getMetroBundler","config","reportEvent","serverRoot","getMetroServerRoot","isWorkspace","targetsOutOfTreePlatform","getPlatformsFromConfig","some","platform","autolinkingModuleResolutionEnabled","experiments","autolinkingModuleResolution","serverActionsEnabled","reactServerFunctions","env","EXPO_UNSTABLE_SERVER_FUNCTIONS","serverComponentsEnabled","reactServerComponentRoutes","EXPO_USE_METRO_REQUIRE","reactCanary","Log","terminalReporter","MetroTerminalReporter","loadUserConfig","overrideConfigPath","EXPO_OVERRIDE_METRO_CONFIG","undefined","resetCache","maxWorkers","server","port","reporter","update","onDemandFilesystem","resolver","unstable_onDemandFilesystem","globalThis","__requireCycleIgnorePatterns","requireCycleIgnorePatterns","transformer","publicPath","baseUrl","platformBundlers","getPlatformBundlers","reduceLogs","shouldReduceLogs","reactCompilerEnabled","reactCompiler","chalk","gray","EXPO_UNSTABLE_TREE_SHAKING","EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH","CommandError","EXPO_UNSTABLE_LOG_BOX","withMetroMultiPlatformAsync","isTsconfigPathsEnabled","tsconfigPaths","isAutolinkingResolverEnabled","isNamedRequiresEnabled","isReactServerComponentsEnabled","path","exporting","flags","serverActions","serverComponents","optimizeGraph","treeshaking","logbox","setEventReporter","logger","metroBundler","getConfig","skipSDKVersionRequirement","metroConfig","metro","getBundler","serverBaseUrl","getUrlCreator","constructUrl","scheme","hostType","middleware","messagesSocket","eventsSocket","websocketEndpoints","createMetroMiddleware","prependMiddleware","createCorsMiddleware","debugMiddleware","debugWebsocketEndpoints","createDebugMiddleware","Object","assign","use","createJsInspectorMiddleware","customEnhanceMiddleware","enhanceMiddleware","metroMiddleware","devtoolsWebsocketEndpoints","createDevToolsPluginWebsocketEndpoint","attachAtlasAsync","resetAtlasFile","tls","secureServerOptions","key","cert","ca","requestCert","watch","address","hmrServer","replaceMetroFileMap","runServer","host","mockServer","atlas","EXPO_ATLAS","workers","originalTransformFile","transformFile","bind","filePath","transformOptions","fileBuffer","pruneCustomTransformOptions","customTransformOptions","__proto__","patchTransformFileForPackedMaps","patchMetroSourceMapStringForPackedMaps","reportMetroEvent","_getSortedModules","graph","modules","dependencies","values","ctx","environment","module","_createModuleId","sort","a","b","hmrJSBundle","default","_prepareMessage","group","changeEvent","isInitialUpdate","revision","revPromise","_bundler","getRevision","revisionId","type","body","formatBundlingError","RevisionNotFoundError","point","delta","updateGraph","_clientGroups","delete","id","client","clients","revisionIds","filter","set","moduleIdContext","hmrUpdate","clientUrl","createModuleId","moduleId","includeAsyncPaths","graphOptions","lazy","_config","unstable_serverRoot","formattedError","messageSocket","split","sep","dom","match","routerRoot","isRouterEntry","test","isRouterModule","resolvedRouterRoot","resolve","isRouterRoute","isAbsolute","startsWith","asyncRoutes","clientBoundaries","CI"],"mappings":";;;;;;;;;;;QAuCaA;eAAAA;;QA+SSC;eAAAA;;QAyUNC;eAAAA;;QA3eMC;eAAAA;;;;yBApL6C;;;;;;;yBAChC;;;;;;;gEAOD;;;;;;;gEAEF;;;;;;;yBACP;;;;;;;yBAEM;;;;;;;yBACiB;;;;;;;yBACO;;;;;;;gEACrC;;;;;;;gEAED;;;;;;iDAEqC;uCAEhB;mCACF;6BACH;uCACK;uCACA;+BACsC;wCAChC;wBACH;qBACrB;qBACA;wBACS;gCACQ;6CACO;2BACV;kCACE;;;;;;AAG7B,MAAMH,QAAQI,IAAAA,cAAM,EAAC,SAAS,CAACC,IAAM;QAC1CA,EAAEL,KAAK;QAcPK,EAAEL,KAAK;KAMR;AAsBD,SAASM,WAAcC,KAAQ;IAC7B,OAAOA;AACT;AAEA;;;;;;;;;CASC,GACD,MAAMC,8BAA8BC,qBAAQ;IAC1C,CAAA,WAAY,CAAgB;IAC5B,CAAA,cAAe,CAAS;IAExB,YA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