@expo/cli 55.0.1 → 55.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/bin/cli +1 -1
- package/build/src/export/exportApp.js +3 -2
- package/build/src/export/exportApp.js.map +1 -1
- package/build/src/export/index.js +33 -10
- package/build/src/export/index.js.map +1 -1
- package/build/src/export/resolveOptions.js +6 -1
- package/build/src/export/resolveOptions.js.map +1 -1
- package/build/src/export/saveAssets.js +28 -9
- package/build/src/export/saveAssets.js.map +1 -1
- package/build/src/utils/array.js +6 -0
- package/build/src/utils/array.js.map +1 -1
- package/build/src/utils/freeport.js +54 -0
- package/build/src/utils/freeport.js.map +1 -0
- package/build/src/utils/port.js +12 -24
- package/build/src/utils/port.js.map +1 -1
- package/build/src/utils/resolveArgs.js +86 -19
- package/build/src/utils/resolveArgs.js.map +1 -1
- package/build/src/utils/telemetry/clients/FetchClient.js +1 -1
- package/build/src/utils/telemetry/utils/context.js +1 -1
- package/package.json +17 -19
package/build/bin/cli
CHANGED
|
@@ -111,7 +111,7 @@ function _interop_require_wildcard(obj, nodeInterop) {
|
|
|
111
111
|
}
|
|
112
112
|
return newObj;
|
|
113
113
|
}
|
|
114
|
-
async function exportAppAsync(projectRoot, { platforms, outputDir, clear, dev, dumpAssetmap, sourceMaps, minify, bytecode, maxWorkers, skipSSG, hostedNative }) {
|
|
114
|
+
async function exportAppAsync(projectRoot, { platforms, outputDir, clear, dev, dumpAssetmap, sourceMaps, inlineSourceMaps, minify, bytecode, maxWorkers, skipSSG, hostedNative }) {
|
|
115
115
|
var _exp_web, _exp_web1;
|
|
116
116
|
// Force the environment during export and do not allow overriding it.
|
|
117
117
|
const environment = dev ? 'development' : 'production';
|
|
@@ -204,7 +204,8 @@ async function exportAppAsync(projectRoot, { platforms, outputDir, clear, dev, d
|
|
|
204
204
|
}),
|
|
205
205
|
mode: dev ? 'development' : 'production',
|
|
206
206
|
engine: isHermes ? 'hermes' : undefined,
|
|
207
|
-
serializerIncludeMaps: sourceMaps,
|
|
207
|
+
serializerIncludeMaps: sourceMaps || inlineSourceMaps,
|
|
208
|
+
inlineSourceMap: inlineSourceMaps,
|
|
208
209
|
bytecode: bytecode && isHermes,
|
|
209
210
|
reactCompiler: !!((_exp_experiments = exp.experiments) == null ? void 0 : _exp_experiments.reactCompiler),
|
|
210
211
|
hosted: hostedNative
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/export/exportApp.ts"],"sourcesContent":["import { getConfig } from '@expo/config';\nimport type { Platform } from '@expo/config';\nimport { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport assert from 'assert';\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport path from 'path';\n\nimport { type PlatformMetadata, createMetadataJson } from './createMetadataJson';\nimport { exportAssetsAsync } from './exportAssets';\nimport {\n addDomBundleToMetadataAsync,\n exportDomComponentAsync,\n transformNativeBundleForMd5Filename,\n transformDomEntryForMd5Filename,\n} from './exportDomComponents';\nimport { assertEngineMismatchAsync, isEnableHermesManaged } from './exportHermes';\nimport {\n exportApiRoutesStandaloneAsync,\n exportFromServerAsync,\n injectScriptTags,\n} from './exportStaticAsync';\nimport { getVirtualFaviconAssetsAsync } from './favicon';\nimport { getPublicExpoManifestAsync } from './getPublicExpoManifest';\nimport { copyPublicFolderAsync } from './publicFolder';\nimport { Options } from './resolveOptions';\nimport {\n ExportAssetMap,\n BundleOutput,\n getFilesFromSerialAssets,\n persistMetroFilesAsync,\n BundleAssetWithFileHashes,\n} from './saveAssets';\nimport { createAssetMap } from './writeContents';\nimport * as Log from '../log';\nimport { WebSupportProjectPrerequisite } from '../start/doctor/web/WebSupportProjectPrerequisite';\nimport { DevServerManager } from '../start/server/DevServerManager';\nimport { MetroBundlerDevServer } from '../start/server/metro/MetroBundlerDevServer';\nimport { getRouterDirectoryModuleIdWithManifest } from '../start/server/metro/router';\nimport { serializeHtmlWithAssets } from '../start/server/metro/serializeHtml';\nimport { getEntryWithServerRoot } from '../start/server/middleware/ManifestMiddleware';\nimport { getBaseUrlFromExpoConfig } from '../start/server/middleware/metroOptions';\nimport { createTemplateHtmlFromExpoConfigAsync } from '../start/server/webTemplate';\nimport { env } from '../utils/env';\nimport { CommandError } from '../utils/errors';\nimport { setNodeEnv } from '../utils/nodeEnv';\n\nexport async function exportAppAsync(\n projectRoot: string,\n {\n platforms,\n outputDir,\n clear,\n dev,\n dumpAssetmap,\n sourceMaps,\n minify,\n bytecode,\n maxWorkers,\n skipSSG,\n hostedNative,\n }: Pick<\n Options,\n | 'dumpAssetmap'\n | 'sourceMaps'\n | 'dev'\n | 'clear'\n | 'outputDir'\n | 'platforms'\n | 'minify'\n | 'bytecode'\n | 'maxWorkers'\n | 'skipSSG'\n | 'hostedNative'\n >\n): Promise<void> {\n // Force the environment during export and do not allow overriding it.\n const environment = dev ? 'development' : 'production';\n process.env.NODE_ENV = environment;\n setNodeEnv(environment);\n\n require('@expo/env').load(projectRoot);\n\n const projectConfig = getConfig(projectRoot);\n const exp = await getPublicExpoManifestAsync(projectRoot, {\n // Web doesn't require validation.\n skipValidation: platforms.length === 1 && platforms[0] === 'web',\n });\n\n if (platforms.includes('web')) {\n await new WebSupportProjectPrerequisite(projectRoot).assertAsync();\n }\n\n const useServerRendering = ['static', 'server'].includes(exp.web?.output ?? '');\n\n if (skipSSG && exp.web?.output !== 'server') {\n throw new CommandError('--no-ssg can only be used with `web.output: server`');\n }\n\n const baseUrl = getBaseUrlFromExpoConfig(exp);\n\n if (!bytecode && (platforms.includes('ios') || platforms.includes('android'))) {\n Log.warn(\n `Bytecode makes the app startup faster, disabling bytecode is highly discouraged and should only be used for debugging purposes.`\n );\n }\n\n // Print out logs\n if (baseUrl) {\n Log.log();\n Log.log(chalk.gray`Using (experimental) base path: ${baseUrl}`);\n // Warn if not using an absolute path.\n if (!baseUrl.startsWith('/')) {\n Log.log(\n chalk.yellow` Base path does not start with a slash. Requests will not be absolute.`\n );\n }\n }\n\n const mode = dev ? 'development' : 'production';\n const publicPath = path.resolve(projectRoot, env.EXPO_PUBLIC_FOLDER);\n const outputPath = path.resolve(projectRoot, outputDir);\n\n // Write the JS bundles to disk, and get the bundle file names (this could change with async chunk loading support).\n\n const files: ExportAssetMap = new Map();\n\n const devServerManager = await DevServerManager.startMetroAsync(projectRoot, {\n minify,\n mode,\n port: 8081,\n isExporting: true,\n location: {},\n resetDevServer: clear,\n maxWorkers,\n });\n\n const devServer = devServerManager.getDefaultDevServer();\n assert(devServer instanceof MetroBundlerDevServer);\n\n const bundles: Partial<Record<Platform, BundleOutput>> = {};\n const domComponentAssetsMetadata: Partial<Record<Platform, PlatformMetadata['assets']>> = {};\n\n const spaPlatforms =\n // TODO: Support server and static rendering for server component exports.\n useServerRendering && !devServer.isReactServerComponentsEnabled\n ? platforms.filter((platform) => platform !== 'web')\n : platforms;\n\n try {\n if (devServer.isReactServerComponentsEnabled) {\n // In RSC mode, we only need these to be in the client dir.\n // TODO: Merge back with other copy after we add SSR.\n try {\n await copyPublicFolderAsync(publicPath, path.join(outputPath, 'client'));\n } catch (error) {\n Log.error('Failed to copy public directory to dist directory');\n throw error;\n }\n } else {\n // NOTE(kitten): The public folder is currently always copied, regardless of targetDomain\n // split. Hence, there's another separate `copyPublicFolderAsync` call below for `web`\n await copyPublicFolderAsync(publicPath, outputPath);\n }\n\n let templateHtml: string | undefined;\n // Can be empty during web-only SSG.\n if (spaPlatforms.length) {\n await Promise.all(\n spaPlatforms.map(async (platform) => {\n // Assert early so the user doesn't have to wait until bundling is complete to find out that\n // Hermes won't be available.\n const isHermes = isEnableHermesManaged(exp, platform);\n if (isHermes) {\n await assertEngineMismatchAsync(projectRoot, exp, platform);\n }\n\n let bundle: {\n artifacts: SerialAsset[];\n assets: readonly BundleAssetWithFileHashes[];\n files?: ExportAssetMap;\n };\n\n try {\n // Run metro bundler and create the JS bundles/source maps.\n bundle = await devServer.nativeExportBundleAsync(\n exp,\n {\n platform,\n splitChunks:\n !env.EXPO_NO_BUNDLE_SPLITTING &&\n ((devServer.isReactServerComponentsEnabled && !bytecode) || platform === 'web'),\n mainModuleName: getEntryWithServerRoot(projectRoot, {\n platform,\n pkg: projectConfig.pkg,\n }),\n mode: dev ? 'development' : 'production',\n engine: isHermes ? 'hermes' : undefined,\n serializerIncludeMaps: sourceMaps,\n bytecode: bytecode && isHermes,\n reactCompiler: !!exp.experiments?.reactCompiler,\n hosted: hostedNative,\n },\n files\n );\n } catch (error) {\n Log.log('');\n if (error instanceof Error) {\n Log.exception(error);\n } else {\n Log.error('Failed to bundle the app');\n Log.log(error as any);\n }\n process.exit(1);\n }\n\n bundles[platform] = bundle;\n\n getFilesFromSerialAssets(bundle.artifacts, {\n includeSourceMaps: sourceMaps,\n files,\n isServerHosted: devServer.isReactServerComponentsEnabled || hostedNative,\n });\n\n // TODO: Remove duplicates...\n const expoDomComponentReferences = bundle.artifacts\n .map((artifact) =>\n Array.isArray(artifact.metadata.expoDomComponentReferences)\n ? artifact.metadata.expoDomComponentReferences\n : []\n )\n .flat();\n await Promise.all(\n // TODO: Make a version of this which uses `this.metro.getBundler().buildGraphForEntries([])` to bundle all the DOM components at once.\n expoDomComponentReferences.map(async (filePath) => {\n const { bundle: platformDomComponentsBundle, htmlOutputName } =\n await exportDomComponentAsync({\n filePath,\n projectRoot,\n dev,\n devServer,\n isHermes,\n includeSourceMaps: sourceMaps,\n exp,\n files,\n useMd5Filename: true,\n });\n\n // Merge the assets from the DOM component into the output assets.\n (bundle.assets as (typeof bundle.assets)[0][]).push(\n ...platformDomComponentsBundle.assets\n );\n\n transformNativeBundleForMd5Filename({\n domComponentReference: filePath,\n nativeBundle: bundle,\n files,\n htmlOutputName,\n });\n domComponentAssetsMetadata[platform] = [\n ...(domComponentAssetsMetadata[platform] || []),\n ...(await addDomBundleToMetadataAsync(platformDomComponentsBundle)),\n ...transformDomEntryForMd5Filename({\n files,\n htmlOutputName,\n }),\n ];\n })\n );\n\n if (platform === 'web') {\n // TODO: Unify with exportStaticAsync\n // TODO: Maybe move to the serializer.\n let html = await serializeHtmlWithAssets({\n isExporting: true,\n resources: bundle.artifacts,\n template: await createTemplateHtmlFromExpoConfigAsync(projectRoot, {\n scripts: [],\n cssLinks: [],\n exp: projectConfig.exp,\n }),\n baseUrl,\n });\n\n // Add the favicon assets to the HTML.\n const modifyHtml = await getVirtualFaviconAssetsAsync(projectRoot, {\n outputDir,\n baseUrl,\n files,\n exp: projectConfig.exp,\n });\n if (modifyHtml) {\n html = modifyHtml(html);\n }\n\n // HACK: This is used for adding SSR shims in React Server Components.\n templateHtml = html;\n\n // Generate SPA-styled HTML file.\n // If web exists, then write the template HTML file.\n files.set('index.html', {\n contents: html,\n targetDomain: devServer.isReactServerComponentsEnabled ? 'server' : 'client',\n });\n }\n })\n );\n\n if (devServer.isReactServerComponentsEnabled) {\n const isWeb = platforms.includes('web');\n\n await exportApiRoutesStandaloneAsync(devServer, {\n files,\n platform: 'web',\n apiRoutesOnly: !isWeb,\n templateHtml,\n });\n }\n\n // TODO: Use same asset system across platforms again.\n const { assets, embeddedHashSet } = await exportAssetsAsync(projectRoot, {\n files,\n exp,\n outputDir: outputPath,\n bundles,\n baseUrl,\n hostedNative,\n });\n\n if (dumpAssetmap) {\n Log.log('Creating asset map');\n files.set('assetmap.json', { contents: JSON.stringify(createAssetMap({ assets })) });\n }\n\n const targetDomain = devServer.isReactServerComponentsEnabled ? 'client/' : '';\n const fileNames = Object.fromEntries(\n Object.entries(bundles).map(([platform, bundle]) => [\n platform,\n bundle.artifacts\n .filter((asset) => asset.type === 'js')\n .map((asset) => targetDomain + asset.filename),\n ])\n );\n\n // Generate a `metadata.json` for EAS Update.\n const contents = createMetadataJson({\n bundles,\n fileNames,\n embeddedHashSet,\n domComponentAssetsMetadata,\n });\n files.set('metadata.json', { contents: JSON.stringify(contents) });\n }\n\n // Additional web-only steps...\n\n if (platforms.includes('web') && useServerRendering) {\n const exportServer = exp.web?.output === 'server';\n\n if (exportServer) {\n // TODO: Remove when this is abstracted into the files map\n await copyPublicFolderAsync(publicPath, path.resolve(outputPath, 'client'));\n }\n\n if (skipSSG) {\n Log.log('Skipping static site generation');\n await exportApiRoutesStandaloneAsync(devServer, {\n files,\n platform: 'web',\n apiRoutesOnly: true,\n });\n\n // Output a placeholder index.html if one doesn't exist in the public directory.\n // This ensures native + API routes have some content at the root URL.\n const placeholderIndex = path.resolve(outputPath, 'client/index.html');\n if (!fs.existsSync(placeholderIndex)) {\n files.set('index.html', {\n contents: `<html><body></body></html>`,\n targetDomain: 'client',\n });\n }\n } else if (\n // TODO: Support static export with RSC.\n !devServer.isReactServerComponentsEnabled\n ) {\n await exportFromServerAsync(projectRoot, devServer, {\n mode,\n files,\n clear: !!clear,\n outputDir: outputPath,\n minify,\n baseUrl,\n includeSourceMaps: sourceMaps,\n routerRoot: getRouterDirectoryModuleIdWithManifest(projectRoot, exp),\n reactCompiler: !!exp.experiments?.reactCompiler,\n exportServer,\n maxWorkers,\n isExporting: true,\n exp: projectConfig.exp,\n });\n }\n }\n } finally {\n await devServerManager.stopAsync();\n }\n\n // Write all files at the end for unified logging.\n await persistMetroFilesAsync(files, outputPath);\n}\n"],"names":["exportAppAsync","projectRoot","platforms","outputDir","clear","dev","dumpAssetmap","sourceMaps","minify","bytecode","maxWorkers","skipSSG","hostedNative","exp","environment","process","env","NODE_ENV","setNodeEnv","require","load","projectConfig","getConfig","getPublicExpoManifestAsync","skipValidation","length","includes","WebSupportProjectPrerequisite","assertAsync","useServerRendering","web","output","CommandError","baseUrl","getBaseUrlFromExpoConfig","Log","warn","log","chalk","gray","startsWith","yellow","mode","publicPath","path","resolve","EXPO_PUBLIC_FOLDER","outputPath","files","Map","devServerManager","DevServerManager","startMetroAsync","port","isExporting","location","resetDevServer","devServer","getDefaultDevServer","assert","MetroBundlerDevServer","bundles","domComponentAssetsMetadata","spaPlatforms","isReactServerComponentsEnabled","filter","platform","copyPublicFolderAsync","join","error","templateHtml","Promise","all","map","isHermes","isEnableHermesManaged","assertEngineMismatchAsync","bundle","nativeExportBundleAsync","splitChunks","EXPO_NO_BUNDLE_SPLITTING","mainModuleName","getEntryWithServerRoot","pkg","engine","undefined","serializerIncludeMaps","reactCompiler","experiments","hosted","Error","exception","exit","getFilesFromSerialAssets","artifacts","includeSourceMaps","isServerHosted","expoDomComponentReferences","artifact","Array","isArray","metadata","flat","filePath","platformDomComponentsBundle","htmlOutputName","exportDomComponentAsync","useMd5Filename","assets","push","transformNativeBundleForMd5Filename","domComponentReference","nativeBundle","addDomBundleToMetadataAsync","transformDomEntryForMd5Filename","html","serializeHtmlWithAssets","resources","template","createTemplateHtmlFromExpoConfigAsync","scripts","cssLinks","modifyHtml","getVirtualFaviconAssetsAsync","set","contents","targetDomain","isWeb","exportApiRoutesStandaloneAsync","apiRoutesOnly","embeddedHashSet","exportAssetsAsync","JSON","stringify","createAssetMap","fileNames","Object","fromEntries","entries","asset","type","filename","createMetadataJson","exportServer","placeholderIndex","fs","existsSync","exportFromServerAsync","routerRoot","getRouterDirectoryModuleIdWithManifest","stopAsync","persistMetroFilesAsync"],"mappings":";;;;+BA+CsBA;;;eAAAA;;;;yBA/CI;;;;;;;gEAGP;;;;;;;gEACD;;;;;;;gEACH;;;;;;;gEACE;;;;;;oCAEyC;8BACxB;qCAM3B;8BAC0D;mCAK1D;yBACsC;uCACF;8BACL;4BAQ/B;+BACwB;6DACV;+CACyB;kCACb;uCACK;wBACiB;+BACf;oCACD;8BACE;6BACa;qBAClC;wBACS;yBACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEpB,eAAeA,eACpBC,WAAmB,EACnB,EACEC,SAAS,EACTC,SAAS,EACTC,KAAK,EACLC,GAAG,EACHC,YAAY,EACZC,UAAU,EACVC,MAAM,EACNC,QAAQ,EACRC,UAAU,EACVC,OAAO,EACPC,YAAY,EAcb;QAmBwDC,UAE1CA;IAnBf,sEAAsE;IACtE,MAAMC,cAAcT,MAAM,gBAAgB;IAC1CU,QAAQC,GAAG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DAA8B,EAACvE,WAAW;oBAC9CT;oBACAkB,UAAU;oBACV+D,eAAe;gBACjB;gBAEA,gFAAgF;gBAChF,sEAAsE;gBACtE,MAAMe,mBAAmBpG,eAAI,CAACC,OAAO,CAACE,YAAY;gBAClD,IAAI,CAACkG,aAAE,CAACC,UAAU,CAACF,mBAAmB;oBACpChG,MAAM4E,GAAG,CAAC,cAAc;wBACtBC,UAAU,CAAC,0BAA0B,CAAC;wBACtCC,cAAc;oBAChB;gBACF;YACF,OAAO,IACL,wCAAwC;YACxC,CAACrE,UAAUO,8BAA8B,EACzC;oBAUmBnD;gBATnB,MAAMsI,IAAAA,wCAAqB,EAAClJ,aAAawD,WAAW;oBAClDf;oBACAM;oBACA5C,OAAO,CAAC,CAACA;oBACTD,WAAW4C;oBACXvC;oBACAyB;oBACA8D,mBAAmBxF;oBACnB6I,YAAYC,IAAAA,8CAAsC,EAACpJ,aAAaY;oBAChE0E,eAAe,CAAC,GAAC1E,mBAAAA,IAAI2E,WAAW,qBAAf3E,iBAAiB0E,aAAa;oBAC/CwD;oBACArI;oBACA4C,aAAa;oBACbzC,KAAKQ,cAAcR,GAAG;gBACxB;YACF;QACF;IACF,SAAU;QACR,MAAMqC,iBAAiBoG,SAAS;IAClC;IAEA,kDAAkD;IAClD,MAAMC,IAAAA,kCAAsB,EAACvG,OAAOD;AACtC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/export/exportApp.ts"],"sourcesContent":["import { getConfig } from '@expo/config';\nimport type { Platform } from '@expo/config';\nimport { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport assert from 'assert';\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport path from 'path';\n\nimport { type PlatformMetadata, createMetadataJson } from './createMetadataJson';\nimport { exportAssetsAsync } from './exportAssets';\nimport {\n addDomBundleToMetadataAsync,\n exportDomComponentAsync,\n transformNativeBundleForMd5Filename,\n transformDomEntryForMd5Filename,\n} from './exportDomComponents';\nimport { assertEngineMismatchAsync, isEnableHermesManaged } from './exportHermes';\nimport {\n exportApiRoutesStandaloneAsync,\n exportFromServerAsync,\n injectScriptTags,\n} from './exportStaticAsync';\nimport { getVirtualFaviconAssetsAsync } from './favicon';\nimport { getPublicExpoManifestAsync } from './getPublicExpoManifest';\nimport { copyPublicFolderAsync } from './publicFolder';\nimport { Options } from './resolveOptions';\nimport {\n ExportAssetMap,\n BundleOutput,\n getFilesFromSerialAssets,\n persistMetroFilesAsync,\n BundleAssetWithFileHashes,\n} from './saveAssets';\nimport { createAssetMap } from './writeContents';\nimport * as Log from '../log';\nimport { WebSupportProjectPrerequisite } from '../start/doctor/web/WebSupportProjectPrerequisite';\nimport { DevServerManager } from '../start/server/DevServerManager';\nimport { MetroBundlerDevServer } from '../start/server/metro/MetroBundlerDevServer';\nimport { getRouterDirectoryModuleIdWithManifest } from '../start/server/metro/router';\nimport { serializeHtmlWithAssets } from '../start/server/metro/serializeHtml';\nimport { getEntryWithServerRoot } from '../start/server/middleware/ManifestMiddleware';\nimport { getBaseUrlFromExpoConfig } from '../start/server/middleware/metroOptions';\nimport { createTemplateHtmlFromExpoConfigAsync } from '../start/server/webTemplate';\nimport { env } from '../utils/env';\nimport { CommandError } from '../utils/errors';\nimport { setNodeEnv } from '../utils/nodeEnv';\n\nexport async function exportAppAsync(\n projectRoot: string,\n {\n platforms,\n outputDir,\n clear,\n dev,\n dumpAssetmap,\n sourceMaps,\n inlineSourceMaps,\n minify,\n bytecode,\n maxWorkers,\n skipSSG,\n hostedNative,\n }: Pick<\n Options,\n | 'dumpAssetmap'\n | 'sourceMaps'\n | 'inlineSourceMaps'\n | 'dev'\n | 'clear'\n | 'outputDir'\n | 'platforms'\n | 'minify'\n | 'bytecode'\n | 'maxWorkers'\n | 'skipSSG'\n | 'hostedNative'\n >\n): Promise<void> {\n // Force the environment during export and do not allow overriding it.\n const environment = dev ? 'development' : 'production';\n process.env.NODE_ENV = environment;\n setNodeEnv(environment);\n\n require('@expo/env').load(projectRoot);\n\n const projectConfig = getConfig(projectRoot);\n const exp = await getPublicExpoManifestAsync(projectRoot, {\n // Web doesn't require validation.\n skipValidation: platforms.length === 1 && platforms[0] === 'web',\n });\n\n if (platforms.includes('web')) {\n await new WebSupportProjectPrerequisite(projectRoot).assertAsync();\n }\n\n const useServerRendering = ['static', 'server'].includes(exp.web?.output ?? '');\n\n if (skipSSG && exp.web?.output !== 'server') {\n throw new CommandError('--no-ssg can only be used with `web.output: server`');\n }\n\n const baseUrl = getBaseUrlFromExpoConfig(exp);\n\n if (!bytecode && (platforms.includes('ios') || platforms.includes('android'))) {\n Log.warn(\n `Bytecode makes the app startup faster, disabling bytecode is highly discouraged and should only be used for debugging purposes.`\n );\n }\n\n // Print out logs\n if (baseUrl) {\n Log.log();\n Log.log(chalk.gray`Using (experimental) base path: ${baseUrl}`);\n // Warn if not using an absolute path.\n if (!baseUrl.startsWith('/')) {\n Log.log(\n chalk.yellow` Base path does not start with a slash. Requests will not be absolute.`\n );\n }\n }\n\n const mode = dev ? 'development' : 'production';\n const publicPath = path.resolve(projectRoot, env.EXPO_PUBLIC_FOLDER);\n const outputPath = path.resolve(projectRoot, outputDir);\n\n // Write the JS bundles to disk, and get the bundle file names (this could change with async chunk loading support).\n\n const files: ExportAssetMap = new Map();\n\n const devServerManager = await DevServerManager.startMetroAsync(projectRoot, {\n minify,\n mode,\n port: 8081,\n isExporting: true,\n location: {},\n resetDevServer: clear,\n maxWorkers,\n });\n\n const devServer = devServerManager.getDefaultDevServer();\n assert(devServer instanceof MetroBundlerDevServer);\n\n const bundles: Partial<Record<Platform, BundleOutput>> = {};\n const domComponentAssetsMetadata: Partial<Record<Platform, PlatformMetadata['assets']>> = {};\n\n const spaPlatforms =\n // TODO: Support server and static rendering for server component exports.\n useServerRendering && !devServer.isReactServerComponentsEnabled\n ? platforms.filter((platform) => platform !== 'web')\n : platforms;\n\n try {\n if (devServer.isReactServerComponentsEnabled) {\n // In RSC mode, we only need these to be in the client dir.\n // TODO: Merge back with other copy after we add SSR.\n try {\n await copyPublicFolderAsync(publicPath, path.join(outputPath, 'client'));\n } catch (error) {\n Log.error('Failed to copy public directory to dist directory');\n throw error;\n }\n } else {\n // NOTE(kitten): The public folder is currently always copied, regardless of targetDomain\n // split. Hence, there's another separate `copyPublicFolderAsync` call below for `web`\n await copyPublicFolderAsync(publicPath, outputPath);\n }\n\n let templateHtml: string | undefined;\n // Can be empty during web-only SSG.\n if (spaPlatforms.length) {\n await Promise.all(\n spaPlatforms.map(async (platform) => {\n // Assert early so the user doesn't have to wait until bundling is complete to find out that\n // Hermes won't be available.\n const isHermes = isEnableHermesManaged(exp, platform);\n if (isHermes) {\n await assertEngineMismatchAsync(projectRoot, exp, platform);\n }\n\n let bundle: {\n artifacts: SerialAsset[];\n assets: readonly BundleAssetWithFileHashes[];\n files?: ExportAssetMap;\n };\n\n try {\n // Run metro bundler and create the JS bundles/source maps.\n bundle = await devServer.nativeExportBundleAsync(\n exp,\n {\n platform,\n splitChunks:\n !env.EXPO_NO_BUNDLE_SPLITTING &&\n ((devServer.isReactServerComponentsEnabled && !bytecode) || platform === 'web'),\n mainModuleName: getEntryWithServerRoot(projectRoot, {\n platform,\n pkg: projectConfig.pkg,\n }),\n mode: dev ? 'development' : 'production',\n engine: isHermes ? 'hermes' : undefined,\n serializerIncludeMaps: sourceMaps || inlineSourceMaps,\n inlineSourceMap: inlineSourceMaps,\n bytecode: bytecode && isHermes,\n reactCompiler: !!exp.experiments?.reactCompiler,\n hosted: hostedNative,\n },\n files\n );\n } catch (error) {\n Log.log('');\n if (error instanceof Error) {\n Log.exception(error);\n } else {\n Log.error('Failed to bundle the app');\n Log.log(error as any);\n }\n process.exit(1);\n }\n\n bundles[platform] = bundle;\n\n getFilesFromSerialAssets(bundle.artifacts, {\n includeSourceMaps: sourceMaps,\n files,\n isServerHosted: devServer.isReactServerComponentsEnabled || hostedNative,\n });\n\n // TODO: Remove duplicates...\n const expoDomComponentReferences = bundle.artifacts\n .map((artifact) =>\n Array.isArray(artifact.metadata.expoDomComponentReferences)\n ? artifact.metadata.expoDomComponentReferences\n : []\n )\n .flat();\n await Promise.all(\n // TODO: Make a version of this which uses `this.metro.getBundler().buildGraphForEntries([])` to bundle all the DOM components at once.\n expoDomComponentReferences.map(async (filePath) => {\n const { bundle: platformDomComponentsBundle, htmlOutputName } =\n await exportDomComponentAsync({\n filePath,\n projectRoot,\n dev,\n devServer,\n isHermes,\n includeSourceMaps: sourceMaps,\n exp,\n files,\n useMd5Filename: true,\n });\n\n // Merge the assets from the DOM component into the output assets.\n (bundle.assets as (typeof bundle.assets)[0][]).push(\n ...platformDomComponentsBundle.assets\n );\n\n transformNativeBundleForMd5Filename({\n domComponentReference: filePath,\n nativeBundle: bundle,\n files,\n htmlOutputName,\n });\n domComponentAssetsMetadata[platform] = [\n ...(domComponentAssetsMetadata[platform] || []),\n ...(await addDomBundleToMetadataAsync(platformDomComponentsBundle)),\n ...transformDomEntryForMd5Filename({\n files,\n htmlOutputName,\n }),\n ];\n })\n );\n\n if (platform === 'web') {\n // TODO: Unify with exportStaticAsync\n // TODO: Maybe move to the serializer.\n let html = await serializeHtmlWithAssets({\n isExporting: true,\n resources: bundle.artifacts,\n template: await createTemplateHtmlFromExpoConfigAsync(projectRoot, {\n scripts: [],\n cssLinks: [],\n exp: projectConfig.exp,\n }),\n baseUrl,\n });\n\n // Add the favicon assets to the HTML.\n const modifyHtml = await getVirtualFaviconAssetsAsync(projectRoot, {\n outputDir,\n baseUrl,\n files,\n exp: projectConfig.exp,\n });\n if (modifyHtml) {\n html = modifyHtml(html);\n }\n\n // HACK: This is used for adding SSR shims in React Server Components.\n templateHtml = html;\n\n // Generate SPA-styled HTML file.\n // If web exists, then write the template HTML file.\n files.set('index.html', {\n contents: html,\n targetDomain: devServer.isReactServerComponentsEnabled ? 'server' : 'client',\n });\n }\n })\n );\n\n if (devServer.isReactServerComponentsEnabled) {\n const isWeb = platforms.includes('web');\n\n await exportApiRoutesStandaloneAsync(devServer, {\n files,\n platform: 'web',\n apiRoutesOnly: !isWeb,\n templateHtml,\n });\n }\n\n // TODO: Use same asset system across platforms again.\n const { assets, embeddedHashSet } = await exportAssetsAsync(projectRoot, {\n files,\n exp,\n outputDir: outputPath,\n bundles,\n baseUrl,\n hostedNative,\n });\n\n if (dumpAssetmap) {\n Log.log('Creating asset map');\n files.set('assetmap.json', { contents: JSON.stringify(createAssetMap({ assets })) });\n }\n\n const targetDomain = devServer.isReactServerComponentsEnabled ? 'client/' : '';\n const fileNames = Object.fromEntries(\n Object.entries(bundles).map(([platform, bundle]) => [\n platform,\n bundle.artifacts\n .filter((asset) => asset.type === 'js')\n .map((asset) => targetDomain + asset.filename),\n ])\n );\n\n // Generate a `metadata.json` for EAS Update.\n const contents = createMetadataJson({\n bundles,\n fileNames,\n embeddedHashSet,\n domComponentAssetsMetadata,\n });\n files.set('metadata.json', { contents: JSON.stringify(contents) });\n }\n\n // Additional web-only steps...\n\n if (platforms.includes('web') && useServerRendering) {\n const exportServer = exp.web?.output === 'server';\n\n if (exportServer) {\n // TODO: Remove when this is abstracted into the files map\n await copyPublicFolderAsync(publicPath, path.resolve(outputPath, 'client'));\n }\n\n if (skipSSG) {\n Log.log('Skipping static site generation');\n await exportApiRoutesStandaloneAsync(devServer, {\n files,\n platform: 'web',\n apiRoutesOnly: true,\n });\n\n // Output a placeholder index.html if one doesn't exist in the public directory.\n // This ensures native + API routes have some content at the root URL.\n const placeholderIndex = path.resolve(outputPath, 'client/index.html');\n if (!fs.existsSync(placeholderIndex)) {\n files.set('index.html', {\n contents: `<html><body></body></html>`,\n targetDomain: 'client',\n });\n }\n } else if (\n // TODO: Support static export with RSC.\n !devServer.isReactServerComponentsEnabled\n ) {\n await exportFromServerAsync(projectRoot, devServer, {\n mode,\n files,\n clear: !!clear,\n outputDir: outputPath,\n minify,\n baseUrl,\n includeSourceMaps: sourceMaps,\n routerRoot: getRouterDirectoryModuleIdWithManifest(projectRoot, exp),\n reactCompiler: !!exp.experiments?.reactCompiler,\n exportServer,\n maxWorkers,\n isExporting: true,\n exp: projectConfig.exp,\n });\n }\n }\n } finally {\n await devServerManager.stopAsync();\n }\n\n // Write all files at the end for unified logging.\n await persistMetroFilesAsync(files, outputPath);\n}\n"],"names":["exportAppAsync","projectRoot","platforms","outputDir","clear","dev","dumpAssetmap","sourceMaps","inlineSourceMaps","minify","bytecode","maxWorkers","skipSSG","hostedNative","exp","environment","process","env","NODE_ENV","setNodeEnv","require","load","projectConfig","getConfig","getPublicExpoManifestAsync","skipValidation","length","includes","WebSupportProjectPrerequisite","assertAsync","useServerRendering","web","output","CommandError","baseUrl","getBaseUrlFromExpoConfig","Log","warn","log","chalk","gray","startsWith","yellow","mode","publicPath","path","resolve","EXPO_PUBLIC_FOLDER","outputPath","files","Map","devServerManager","DevServerManager","startMetroAsync","port","isExporting","location","resetDevServer","devServer","getDefaultDevServer","assert","MetroBundlerDevServer","bundles","domComponentAssetsMetadata","spaPlatforms","isReactServerComponentsEnabled","filter","platform","copyPublicFolderAsync","join","error","templateHtml","Promise","all","map","isHermes","isEnableHermesManaged","assertEngineMismatchAsync","bundle","nativeExportBundleAsync","splitChunks","EXPO_NO_BUNDLE_SPLITTING","mainModuleName","getEntryWithServerRoot","pkg","engine","undefined","serializerIncludeMaps","inlineSourceMap","reactCompiler","experiments","hosted","Error","exception","exit","getFilesFromSerialAssets","artifacts","includeSourceMaps","isServerHosted","expoDomComponentReferences","artifact","Array","isArray","metadata","flat","filePath","platformDomComponentsBundle","htmlOutputName","exportDomComponentAsync","useMd5Filename","assets","push","transformNativeBundleForMd5Filename","domComponentReference","nativeBundle","addDomBundleToMetadataAsync","transformDomEntryForMd5Filename","html","serializeHtmlWithAssets","resources","template","createTemplateHtmlFromExpoConfigAsync","scripts","cssLinks","modifyHtml","getVirtualFaviconAssetsAsync","set","contents","targetDomain","isWeb","exportApiRoutesStandaloneAsync","apiRoutesOnly","embeddedHashSet","exportAssetsAsync","JSON","stringify","createAssetMap","fileNames","Object","fromEntries","entries","asset","type","filename","createMetadataJson","exportServer","placeholderIndex","fs","existsSync","exportFromServerAsync","routerRoot","getRouterDirectoryModuleIdWithManifest","stopAsync","persistMetroFilesAsync"],"mappings":";;;;+BA+CsBA;;;eAAAA;;;;yBA/CI;;;;;;;gEAGP;;;;;;;gEACD;;;;;;;gEACH;;;;;;;gEACE;;;;;;oCAEyC;8BACxB;qCAM3B;8BAC0D;mCAK1D;yBACsC;uCACF;8BACL;4BAQ/B;+BACwB;6DACV;+CACyB;kCACb;uCACK;wBACiB;+BACf;oCACD;8BACE;6BACa;qBAClC;wBACS;yBACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEpB,eAAeA,eACpBC,WAAmB,EACnB,EACEC,SAAS,EACTC,SAAS,EACTC,KAAK,EACLC,GAAG,EACHC,YAAY,EACZC,UAAU,EACVC,gBAAgB,EAChBC,MAAM,EACNC,QAAQ,EACRC,UAAU,EACVC,OAAO,EACPC,YAAY,EAeb;QAmBwDC,UAE1CA;IAnBf,sEAAsE;IACtE,MAAMC,cAAcV,MAAM,gBAAgB;IAC1CW,QAAQC,GAAG,CAACC,QAAQ,GAAGH;IACvBI,IAAAA,mBAAU,EAACJ;IAEXK,QAAQ,aAAaC,IAAI,CAACpB;IAE1B,MAAMqB,gBAAgBC,IAAAA,mBAAS,EAACtB;IAChC,MAAMa,MAAM,MAAMU,IAAAA,iDAA0B,EAACvB,aAAa;QACxD,kCAAkC;QAClCwB,gBAAgBvB,UAAUwB,MAAM,KAAK,KAAKxB,SAAS,CAAC,EAAE,KAAK;IAC7D;IAEA,IAAIA,UAAUyB,QAAQ,CAAC,QAAQ;QAC7B,MAAM,IAAIC,4DAA6B,CAAC3B,aAAa4B,WAAW;IAClE;IAEA,MAAMC,qBAAqB;QAAC;QAAU;KAAS,CAACH,QAAQ,CAACb,EAAAA,WAAAA,IAAIiB,GAAG,qBAAPjB,SAASkB,MAAM,KAAI;IAE5E,IAAIpB,WAAWE,EAAAA,YAAAA,IAAIiB,GAA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1F;oBACnB+I,YAAYC,IAAAA,8CAAsC,EAACtJ,aAAaa;oBAChE2E,eAAe,CAAC,GAAC3E,mBAAAA,IAAI4E,WAAW,qBAAf5E,iBAAiB2E,aAAa;oBAC/CwD;oBACAtI;oBACA4C,aAAa;oBACbzC,KAAKQ,cAAcR,GAAG;gBACxB;YACF;QACF;IACF,SAAU;QACR,MAAMqC,iBAAiBqG,SAAS;IAClC;IAEA,kDAAkD;IAClD,MAAMC,IAAAA,kCAAsB,EAACxG,OAAOD;AACtC"}
|
|
@@ -16,6 +16,13 @@ function _chalk() {
|
|
|
16
16
|
};
|
|
17
17
|
return data;
|
|
18
18
|
}
|
|
19
|
+
function _path() {
|
|
20
|
+
const data = /*#__PURE__*/ _interop_require_default(require("path"));
|
|
21
|
+
_path = function() {
|
|
22
|
+
return data;
|
|
23
|
+
};
|
|
24
|
+
return data;
|
|
25
|
+
}
|
|
19
26
|
const _args = require("../utils/args");
|
|
20
27
|
const _errors = require("../utils/errors");
|
|
21
28
|
function _interop_require_default(obj) {
|
|
@@ -65,13 +72,12 @@ function _interop_require_wildcard(obj, nodeInterop) {
|
|
|
65
72
|
return newObj;
|
|
66
73
|
}
|
|
67
74
|
const expoExport = async (argv)=>{
|
|
68
|
-
const
|
|
75
|
+
const rawArgsMap = {
|
|
69
76
|
// Types
|
|
70
77
|
'--help': Boolean,
|
|
71
78
|
'--clear': Boolean,
|
|
72
79
|
'--dump-assetmap': Boolean,
|
|
73
80
|
'--dev': Boolean,
|
|
74
|
-
'--source-maps': Boolean,
|
|
75
81
|
'--max-workers': Number,
|
|
76
82
|
'--output-dir': String,
|
|
77
83
|
'--platform': [
|
|
@@ -88,15 +94,16 @@ const expoExport = async (argv)=>{
|
|
|
88
94
|
'--experimental-bundle': Boolean,
|
|
89
95
|
// Aliases
|
|
90
96
|
'-h': '--help',
|
|
91
|
-
'-s': '--source-maps',
|
|
92
97
|
// '-d': '--dump-assetmap',
|
|
93
98
|
'-c': '--clear',
|
|
94
99
|
'-p': '--platform',
|
|
95
100
|
// Interop with Metro docs and RedBox errors.
|
|
96
|
-
'--reset-cache': '--clear'
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
101
|
+
'--reset-cache': '--clear'
|
|
102
|
+
};
|
|
103
|
+
const args = (0, _args.assertWithOptionsArgs)(rawArgsMap, {
|
|
104
|
+
argv,
|
|
105
|
+
permissive: true
|
|
106
|
+
});
|
|
100
107
|
if (args['--help']) {
|
|
101
108
|
(0, _args.printHelp)(`Export the static files of the app for hosting it on a web server`, (0, _chalk().default)`npx expo export {dim <dir>}`, [
|
|
102
109
|
(0, _chalk().default)`<dir> Directory of the Expo project. {dim Default: Current working directory}`,
|
|
@@ -108,14 +115,30 @@ const expoExport = async (argv)=>{
|
|
|
108
115
|
`--dump-assetmap Emit an asset map for further processing`,
|
|
109
116
|
`--no-ssg, --api-only Skip exporting static HTML files and only export API routes for web`,
|
|
110
117
|
(0, _chalk().default)`-p, --platform <platform> Options: android, ios, web, all. {dim Default: all}`,
|
|
111
|
-
`-s, --source-maps
|
|
118
|
+
(0, _chalk().default)`-s, --source-maps [mode] Emit JavaScript source maps. {dim Options: true, false, inline, external. Default: false}`,
|
|
112
119
|
`-c, --clear Clear the bundler cache`,
|
|
113
120
|
`-h, --help Usage info`
|
|
114
121
|
].join('\n'));
|
|
115
122
|
}
|
|
116
|
-
|
|
123
|
+
// Handle --source-maps which can be a string or boolean (e.g., --source-maps or --source-maps inline)
|
|
124
|
+
const { resolveStringOrBooleanArgsAsync } = await Promise.resolve().then(()=>/*#__PURE__*/ _interop_require_wildcard(require("../utils/resolveArgs.js")));
|
|
125
|
+
const parsed = await resolveStringOrBooleanArgsAsync(argv ?? [], rawArgsMap, {
|
|
126
|
+
// Restrict to 'true', 'false', 'inline', 'external'. Other values are treated as project root.
|
|
127
|
+
'--source-maps': [
|
|
128
|
+
Boolean,
|
|
129
|
+
'inline',
|
|
130
|
+
'external'
|
|
131
|
+
],
|
|
132
|
+
'-s': '--source-maps',
|
|
133
|
+
// Deprecated
|
|
134
|
+
'--dump-sourcemap': '--source-maps'
|
|
135
|
+
}).catch(_errors.logCmdError);
|
|
136
|
+
const projectRoot = _path().default.resolve(parsed.projectRoot);
|
|
117
137
|
const { resolveOptionsAsync } = await Promise.resolve().then(()=>/*#__PURE__*/ _interop_require_wildcard(require("./resolveOptions.js")));
|
|
118
|
-
const options = await resolveOptionsAsync(projectRoot,
|
|
138
|
+
const options = await resolveOptionsAsync(projectRoot, {
|
|
139
|
+
...args,
|
|
140
|
+
'--source-maps': parsed.args['--source-maps']
|
|
141
|
+
}).catch(_errors.logCmdError);
|
|
119
142
|
const { exportAsync } = await Promise.resolve().then(()=>/*#__PURE__*/ _interop_require_wildcard(require("./exportAsync.js")));
|
|
120
143
|
return exportAsync(projectRoot, options).catch(_errors.logCmdError);
|
|
121
144
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/export/index.ts"],"sourcesContent":["#!/usr/bin/env node\nimport chalk from 'chalk';\n\nimport { Command } from '../../bin/cli';\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../src/export/index.ts"],"sourcesContent":["#!/usr/bin/env node\nimport arg from 'arg';\nimport chalk from 'chalk';\nimport path from 'path';\n\nimport { Command } from '../../bin/cli';\nimport { assertWithOptionsArgs, printHelp } from '../utils/args';\nimport { logCmdError } from '../utils/errors';\n\nexport const expoExport: Command = async (argv) => {\n const rawArgsMap: arg.Spec = {\n // Types\n '--help': Boolean,\n '--clear': Boolean,\n '--dump-assetmap': Boolean,\n '--dev': Boolean,\n '--max-workers': Number,\n '--output-dir': String,\n '--platform': [String],\n '--no-minify': Boolean,\n '--no-bytecode': Boolean,\n '--no-ssg': Boolean,\n '--api-only': Boolean,\n '--unstable-hosted-native': Boolean,\n\n // Hack: This is added because EAS CLI always includes the flag.\n // If supplied, we'll do nothing with the value, but at least the process won't crash.\n // Note that we also don't show this value in the `--help` prompt since we don't want people to use it.\n '--experimental-bundle': Boolean,\n\n // Aliases\n '-h': '--help',\n // '-d': '--dump-assetmap',\n '-c': '--clear',\n '-p': '--platform',\n // Interop with Metro docs and RedBox errors.\n '--reset-cache': '--clear',\n };\n\n const args = assertWithOptionsArgs(rawArgsMap, {\n argv,\n permissive: true,\n });\n\n if (args['--help']) {\n printHelp(\n `Export the static files of the app for hosting it on a web server`,\n chalk`npx expo export {dim <dir>}`,\n [\n chalk`<dir> Directory of the Expo project. {dim Default: Current working directory}`,\n chalk`--output-dir <dir> The directory to export the static files to. {dim Default: dist}`,\n `--dev Configure static files for developing locally using a non-https server`,\n `--no-minify Prevent minifying source`,\n `--no-bytecode Prevent generating Hermes bytecode`,\n `--max-workers <number> Maximum number of tasks to allow the bundler to spawn`,\n `--dump-assetmap Emit an asset map for further processing`,\n `--no-ssg, --api-only Skip exporting static HTML files and only export API routes for web`,\n chalk`-p, --platform <platform> Options: android, ios, web, all. {dim Default: all}`,\n chalk`-s, --source-maps [mode] Emit JavaScript source maps. {dim Options: true, false, inline, external. Default: false}`,\n `-c, --clear Clear the bundler cache`,\n `-h, --help Usage info`,\n ].join('\\n')\n );\n }\n\n // Handle --source-maps which can be a string or boolean (e.g., --source-maps or --source-maps inline)\n const { resolveStringOrBooleanArgsAsync } = await import('../utils/resolveArgs.js');\n const parsed = await resolveStringOrBooleanArgsAsync(argv ?? [], rawArgsMap, {\n // Restrict to 'true', 'false', 'inline', 'external'. Other values are treated as project root.\n '--source-maps': [Boolean, 'inline', 'external'],\n '-s': '--source-maps',\n // Deprecated\n '--dump-sourcemap': '--source-maps',\n }).catch(logCmdError);\n\n const projectRoot = path.resolve(parsed.projectRoot);\n const { resolveOptionsAsync } = await import('./resolveOptions.js');\n const options = await resolveOptionsAsync(projectRoot, {\n ...args,\n '--source-maps': parsed.args['--source-maps'],\n }).catch(logCmdError);\n\n const { exportAsync } = await import('./exportAsync.js');\n return exportAsync(projectRoot, options).catch(logCmdError);\n};\n"],"names":["expoExport","argv","rawArgsMap","Boolean","Number","String","args","assertWithOptionsArgs","permissive","printHelp","chalk","join","resolveStringOrBooleanArgsAsync","parsed","catch","logCmdError","projectRoot","path","resolve","resolveOptionsAsync","options","exportAsync"],"mappings":";;;;;+BASaA;;;eAAAA;;;;gEAPK;;;;;;;gEACD;;;;;;sBAGgC;wBACrB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAErB,MAAMA,aAAsB,OAAOC;IACxC,MAAMC,aAAuB;QAC3B,QAAQ;QACR,UAAUC;QACV,WAAWA;QACX,mBAAmBA;QACnB,SAASA;QACT,iBAAiBC;QACjB,gBAAgBC;QAChB,cAAc;YAACA;SAAO;QACtB,eAAeF;QACf,iBAAiBA;QACjB,YAAYA;QACZ,cAAcA;QACd,4BAA4BA;QAE5B,gEAAgE;QAChE,sFAAsF;QACtF,uGAAuG;QACvG,yBAAyBA;QAEzB,UAAU;QACV,MAAM;QACN,2BAA2B;QAC3B,MAAM;QACN,MAAM;QACN,6CAA6C;QAC7C,iBAAiB;IACnB;IAEA,MAAMG,OAAOC,IAAAA,2BAAqB,EAACL,YAAY;QAC7CD;QACAO,YAAY;IACd;IAEA,IAAIF,IAAI,CAAC,SAAS,EAAE;QAClBG,IAAAA,eAAS,EACP,CAAC,iEAAiE,CAAC,EACnEC,IAAAA,gBAAK,CAAA,CAAC,2BAA2B,CAAC,EAClC;YACEA,IAAAA,gBAAK,CAAA,CAAC,kGAAkG,CAAC;YACzGA,IAAAA,gBAAK,CAAA,CAAC,2FAA2F,CAAC;YAClG,CAAC,iGAAiG,CAAC;YACnG,CAAC,mDAAmD,CAAC;YACrD,CAAC,6DAA6D,CAAC;YAC/D,CAAC,gFAAgF,CAAC;YAClF,CAAC,mEAAmE,CAAC;YACrE,CAAC,8FAA8F,CAAC;YAChGA,IAAAA,gBAAK,CAAA,CAAC,8EAA8E,CAAC;YACrFA,IAAAA,gBAAK,CAAA,CAAC,oHAAoH,CAAC;YAC3H,CAAC,kDAAkD,CAAC;YACpD,CAAC,qCAAqC,CAAC;SACxC,CAACC,IAAI,CAAC;IAEX;IAEA,sGAAsG;IACtG,MAAM,EAAEC,+BAA+B,EAAE,GAAG,MAAM,mEAAA,QAAO;IACzD,MAAMC,SAAS,MAAMD,gCAAgCX,QAAQ,EAAE,EAAEC,YAAY;QAC3E,+FAA+F;QAC/F,iBAAiB;YAACC;YAAS;YAAU;SAAW;QAChD,MAAM;QACN,aAAa;QACb,oBAAoB;IACtB,GAAGW,KAAK,CAACC,mBAAW;IAEpB,MAAMC,cAAcC,eAAI,CAACC,OAAO,CAACL,OAAOG,WAAW;IACnD,MAAM,EAAEG,mBAAmB,EAAE,GAAG,MAAM,mEAAA,QAAO;IAC7C,MAAMC,UAAU,MAAMD,oBAAoBH,aAAa;QACrD,GAAGV,IAAI;QACP,iBAAiBO,OAAOP,IAAI,CAAC,gBAAgB;IAC/C,GAAGQ,KAAK,CAACC,mBAAW;IAEpB,MAAM,EAAEM,WAAW,EAAE,GAAG,MAAM,mEAAA,QAAO;IACrC,OAAOA,YAAYL,aAAaI,SAASN,KAAK,CAACC,mBAAW;AAC5D"}
|
|
@@ -69,6 +69,10 @@ async function resolveOptionsAsync(projectRoot, args) {
|
|
|
69
69
|
});
|
|
70
70
|
const platformBundlers = (0, _platformBundlers.getPlatformBundlers)(projectRoot, exp);
|
|
71
71
|
const platforms = resolvePlatformOption(exp, platformBundlers, args['--platform']);
|
|
72
|
+
// --source-maps can be true, "external", or "inline"
|
|
73
|
+
const sourceMapsArg = args['--source-maps'];
|
|
74
|
+
const sourceMaps = !!sourceMapsArg;
|
|
75
|
+
const inlineSourceMaps = sourceMapsArg === 'inline';
|
|
72
76
|
return {
|
|
73
77
|
platforms,
|
|
74
78
|
hostedNative: !!args['--unstable-hosted-native'],
|
|
@@ -79,7 +83,8 @@ async function resolveOptionsAsync(projectRoot, args) {
|
|
|
79
83
|
dev: !!args['--dev'],
|
|
80
84
|
maxWorkers: args['--max-workers'],
|
|
81
85
|
dumpAssetmap: !!args['--dump-assetmap'],
|
|
82
|
-
sourceMaps
|
|
86
|
+
sourceMaps,
|
|
87
|
+
inlineSourceMaps,
|
|
83
88
|
skipSSG: !!args['--no-ssg'] || !!args['--api-only']
|
|
84
89
|
};
|
|
85
90
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/export/resolveOptions.ts"],"sourcesContent":["import { ExpoConfig, getConfig, Platform } from '@expo/config';\n\nimport { getPlatformBundlers, PlatformBundlers } 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 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 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
|
|
1
|
+
{"version":3,"sources":["../../../src/export/resolveOptions.ts"],"sourcesContent":["import { ExpoConfig, getConfig, Platform } from '@expo/config';\n\nimport { getPlatformBundlers, PlatformBundlers } 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":";;;;;;;;;;;IA+EsBA,mBAAmB;eAAnBA;;IA1DNC,qBAAqB;eAArBA;;;;yBArBgC;;;;;;kCAEM;wBACzB;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,i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Bc,YAAYd,IAAI,CAAC,gBAAgB;QACjCe,cAAc,CAAC,CAACf,IAAI,CAAC,kBAAkB;QACvCM;QACAC;QACAS,SAAS,CAAC,CAAChB,IAAI,CAAC,WAAW,IAAI,CAAC,CAACA,IAAI,CAAC,aAAa;IACrD;AACF"}
|
|
@@ -42,13 +42,6 @@ function _path() {
|
|
|
42
42
|
};
|
|
43
43
|
return data;
|
|
44
44
|
}
|
|
45
|
-
function _prettybytes() {
|
|
46
|
-
const data = /*#__PURE__*/ _interop_require_default(require("pretty-bytes"));
|
|
47
|
-
_prettybytes = function() {
|
|
48
|
-
return data;
|
|
49
|
-
};
|
|
50
|
-
return data;
|
|
51
|
-
}
|
|
52
45
|
const _log = require("../log");
|
|
53
46
|
const _env = require("../utils/env");
|
|
54
47
|
function _interop_require_default(obj) {
|
|
@@ -56,6 +49,32 @@ function _interop_require_default(obj) {
|
|
|
56
49
|
default: obj
|
|
57
50
|
};
|
|
58
51
|
}
|
|
52
|
+
let bytesFormatter;
|
|
53
|
+
const prettyBytes = (bytes)=>{
|
|
54
|
+
try {
|
|
55
|
+
if (bytesFormatter === undefined && typeof Intl === 'object') {
|
|
56
|
+
bytesFormatter = new Intl.NumberFormat('en', {
|
|
57
|
+
notation: 'compact',
|
|
58
|
+
style: 'unit',
|
|
59
|
+
unit: 'byte',
|
|
60
|
+
unitDisplay: 'narrow'
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
if (bytesFormatter != null) {
|
|
64
|
+
return bytesFormatter.format(bytes);
|
|
65
|
+
}
|
|
66
|
+
} catch {
|
|
67
|
+
bytesFormatter = null;
|
|
68
|
+
}
|
|
69
|
+
// Fall back if ICU is unavailable, which is rare but possible with custom Node.js builds
|
|
70
|
+
if (bytes >= 900000) {
|
|
71
|
+
return `${(bytes / 1000000).toFixed(1)}MB`;
|
|
72
|
+
} else if (bytes >= 900) {
|
|
73
|
+
return `${(bytes / 1000).toFixed(1)}KB`;
|
|
74
|
+
} else {
|
|
75
|
+
return `${bytes}B`;
|
|
76
|
+
}
|
|
77
|
+
};
|
|
59
78
|
const BLT = '\u203A';
|
|
60
79
|
async function persistMetroFilesAsync(files, outputDir) {
|
|
61
80
|
if (!files.size) {
|
|
@@ -95,7 +114,7 @@ async function persistMetroFilesAsync(files, outputDir) {
|
|
|
95
114
|
};
|
|
96
115
|
const sizeStr = (contents)=>{
|
|
97
116
|
const length = contentSize(contents);
|
|
98
|
-
const size = _chalk().default.gray`(${(
|
|
117
|
+
const size = _chalk().default.gray`(${prettyBytes(length)})`;
|
|
99
118
|
return size;
|
|
100
119
|
};
|
|
101
120
|
// TODO: If any Expo Router is used, then use a new style which is more simple:
|
|
@@ -118,7 +137,7 @@ async function persistMetroFilesAsync(files, outputDir) {
|
|
|
118
137
|
const averageContentSize = assets.reduce((sum, [, { contents }])=>sum + contentSize(contents), 0) / assets.length;
|
|
119
138
|
_log.Log.log(assetId, _chalk().default.gray(`(${[
|
|
120
139
|
assets.length > 1 ? `${assets.length} variations` : '',
|
|
121
|
-
`${(
|
|
140
|
+
`${prettyBytes(averageContentSize)}`
|
|
122
141
|
].filter(Boolean).join(' | ')})`));
|
|
123
142
|
}
|
|
124
143
|
}
|
|
@@ -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';\nimport prettyBytes from 'pretty-bytes';\n\nimport { Log } from '../log';\nimport { env } from '../utils/env';\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","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","prettyBytes","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","undefined"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAyTeA,wBAAwB;eAAxBA;;IAhQMC,sBAAsB;eAAtBA;;;;gEAtDJ;;;;;;;gEACH;;;;;;;gEACE;;;;;;;gEACO;;;;;;qBAEJ;qBACA;;;;;;AAEpB,MAAMC,MAAM;AA8CL,eAAeD,uBAAuBE,KAAqB,EAAEC,SAAiB;IACnF,IAAI,CAACD,MAAME,IAAI,EAAE;QACf;IACF;IACA,MAAMC,aAAE,CAACC,QAAQ,CAACC,KAAK,CAACC,eAAI,CAACC,IAAI,CAACN,YAAY;QAAEO,WAAW;IAAK;IAEhE,iBAAiB;IACjB,WAAW;IACX,oBAAoB;IACpB,4FAA4F;IAC5F,MAAM;IACN,KAAK;IAEL,MAAMC,eAAkD,EAAE;IAC1D,MAAMC,kBAAqD,EAAE;IAC7D,MAAMC,oBAAuD,EAAE;IAC/D,MAAMC,eAAkD,EAAE;IAC1D,MAAMC,aAAgD,EAAE;IACxD,MAAMC,gBAAmD,EAAE;IAC3D,MAAMC,mBAAsD,EAAE;IAE9D,IAAIC,kBAAkB;IACtB,KAAK,MAAMC,SAASjB,MAAMkB,OAAO,GAAI;QACnCF,kBAAkBA,mBAAmBC,KAAK,CAAC,EAAE,CAACE,YAAY,KAAK;QAC/D,IAAIF,KAAK,CAAC,EAAE,CAACG,OAAO,EAAEX,aAAaY,IAAI,CAACJ;aACnC,IAAIA,KAAK,CAAC,EAAE,CAACK,OAAO,IAAI,MAAMV,aAAaS,IAAI,CAACJ;aAChD,IAAIA,KAAK,CAAC,EAAE,CAACM,YAAY,IAAI,MAAMZ,kBAAkBU,IAAI,CAACJ;aAC1D,IAAIA,KAAK,CAAC,EAAE,CAACO,UAAU,IAAI,MAAMd,gBAAgBW,IAAI,CAACJ;aACtD,IAAIA,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ACnC8C,GAAG,CAAC,OAAO,CAACC,MAAM,EAAE9D,QAAQ,EAAEX,YAAY,EAAE,CAAC;QAC5C,qEAAqE;QACrE,MAAM0E,SAAS,AAAC7E,mBAAmBG,gBAAiB;QACpD,MAAM2E,aAAaxF,eAAI,CAACC,IAAI,CAACN,WAAW4F,QAAQD;QAChD,MAAMzF,aAAE,CAACC,QAAQ,CAACC,KAAK,CAACC,eAAI,CAACyF,OAAO,CAACD,aAAa;YAAEtF,WAAW;QAAK;QACpE,MAAML,aAAE,CAACC,QAAQ,CAAC4F,SAAS,CAACF,YAAYhE;IAC1C;IAGJqB,QAAG,CAACC,GAAG,CAAC;AACV;AAEA,SAASxB,QAAWqE,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,KAAKhF,IAAI,CAAC8E;QACVR,IAAI1B,GAAG,CAACmC,OAAOC;IACjB;IACA,OAAOV;AACT;AAGO,SAAS9F,yBACdyG,SAAwB,EACxB,EACEC,iBAAiB,EACjBvG,QAAQ,IAAI0D,KAAK,EACjBK,QAAQ,EACRyC,iBAAiBzC,aAAa,KAAK,EAMpC;IAEDuC,UAAU1C,OAAO,CAAC,CAAC6C;QACjB,IAAIA,SAASC,IAAI,KAAK,gBAAgB;YACpC;QACF;QACA1G,MAAMiE,GAAG,CAACwC,SAAStB,QAAQ,EAAE;YAC3BrD,UAAU2E,SAASE,MAAM;YACzBC,gBAAgBH,SAASG,cAAc;YACvCzF,cAAcqF,iBAAiB,WAAWK;QAC5C;IACF;IAEA,OAAO7G;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 { 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;;;;;;;;;;;IAoVeA,wBAAwB;eAAxBA;;IAhQMC,sBAAsB;eAAtBA;;;;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,OAA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@ _export(exports, {
|
|
|
21
21
|
intersecting: function() {
|
|
22
22
|
return intersecting;
|
|
23
23
|
},
|
|
24
|
+
replaceAllValues: function() {
|
|
25
|
+
return replaceAllValues;
|
|
26
|
+
},
|
|
24
27
|
replaceValue: function() {
|
|
25
28
|
return replaceValue;
|
|
26
29
|
},
|
|
@@ -53,6 +56,9 @@ function replaceValue(values, original, replacement) {
|
|
|
53
56
|
}
|
|
54
57
|
return values;
|
|
55
58
|
}
|
|
59
|
+
function replaceAllValues(values, original, replacement) {
|
|
60
|
+
return values.map((value)=>value === original ? replacement : value);
|
|
61
|
+
}
|
|
56
62
|
function uniqBy(array, key) {
|
|
57
63
|
const seen = {};
|
|
58
64
|
return array.filter((item)=>{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/array.ts"],"sourcesContent":["/** Returns the last index of an item based on a given criteria. */\nexport function findLastIndex<T>(array: T[], predicate: (item: T) => boolean) {\n for (let i = array.length - 1; i >= 0; i--) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return -1;\n}\n\n/** Returns a list of items that intersect between two given arrays. */\nexport function intersecting<T>(a: T[], b: T[]): T[] {\n const [c, d] = a.length > b.length ? [a, b] : [b, a];\n return c.filter((value) => d.includes(value));\n}\n\nexport function replaceValue<T>(values: T[], original: T, replacement: T): T[] {\n const index = values.indexOf(original);\n if (index > -1) {\n values[index] = replacement;\n }\n return values;\n}\n\n/** lodash.uniqBy */\nexport function uniqBy<T>(array: T[], key: (item: T) => string): T[] {\n const seen: { [key: string]: boolean } = {};\n return array.filter((item) => {\n const k = key(item);\n if (seen[k]) {\n return false;\n }\n seen[k] = true;\n return true;\n });\n}\n\n/** `lodash.chunk` */\nexport function chunk<T>(array: T[], size: number): T[][] {\n const chunked = [];\n let index = 0;\n while (index < array.length) {\n chunked.push(array.slice(index, (index += size)));\n }\n return chunked;\n}\n\n/** `lodash.groupBy` */\nexport function groupBy<T, K extends keyof any>(list: T[], getKey: (item: T) => K): Record<K, T[]> {\n return list.reduce(\n (previous, currentItem) => {\n const group = getKey(currentItem);\n if (!previous[group]) {\n previous[group] = [];\n }\n previous[group].push(currentItem);\n return previous;\n },\n {} as Record<K, T[]>\n );\n}\n"],"names":["chunk","findLastIndex","groupBy","intersecting","replaceValue","uniqBy","array","predicate","i","length","a","b","c","d","filter","value","includes","values","original","replacement","index","indexOf","key","seen","item","k","size","chunked","push","slice","list","getKey","reduce","previous","currentItem","group"],"mappings":"AAAA,iEAAiE;;;;;;;;;;;
|
|
1
|
+
{"version":3,"sources":["../../../src/utils/array.ts"],"sourcesContent":["/** Returns the last index of an item based on a given criteria. */\nexport function findLastIndex<T>(array: T[], predicate: (item: T) => boolean) {\n for (let i = array.length - 1; i >= 0; i--) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return -1;\n}\n\n/** Returns a list of items that intersect between two given arrays. */\nexport function intersecting<T>(a: T[], b: T[]): T[] {\n const [c, d] = a.length > b.length ? [a, b] : [b, a];\n return c.filter((value) => d.includes(value));\n}\n\nexport function replaceValue<T>(values: T[], original: T, replacement: T): T[] {\n const index = values.indexOf(original);\n if (index > -1) {\n values[index] = replacement;\n }\n return values;\n}\n\nexport function replaceAllValues<T>(values: T[], original: T, replacement: T): T[] {\n return values.map((value) => (value === original ? replacement : value));\n}\n\n/** lodash.uniqBy */\nexport function uniqBy<T>(array: T[], key: (item: T) => string): T[] {\n const seen: { [key: string]: boolean } = {};\n return array.filter((item) => {\n const k = key(item);\n if (seen[k]) {\n return false;\n }\n seen[k] = true;\n return true;\n });\n}\n\n/** `lodash.chunk` */\nexport function chunk<T>(array: T[], size: number): T[][] {\n const chunked = [];\n let index = 0;\n while (index < array.length) {\n chunked.push(array.slice(index, (index += size)));\n }\n return chunked;\n}\n\n/** `lodash.groupBy` */\nexport function groupBy<T, K extends keyof any>(list: T[], getKey: (item: T) => K): Record<K, T[]> {\n return list.reduce(\n (previous, currentItem) => {\n const group = getKey(currentItem);\n if (!previous[group]) {\n previous[group] = [];\n }\n previous[group].push(currentItem);\n return previous;\n },\n {} as Record<K, T[]>\n );\n}\n"],"names":["chunk","findLastIndex","groupBy","intersecting","replaceAllValues","replaceValue","uniqBy","array","predicate","i","length","a","b","c","d","filter","value","includes","values","original","replacement","index","indexOf","map","key","seen","item","k","size","chunked","push","slice","list","getKey","reduce","previous","currentItem","group"],"mappings":"AAAA,iEAAiE;;;;;;;;;;;IA0CjDA,KAAK;eAALA;;IAzCAC,aAAa;eAAbA;;IAmDAC,OAAO;eAAPA;;IAzCAC,YAAY;eAAZA;;IAaAC,gBAAgB;eAAhBA;;IARAC,YAAY;eAAZA;;IAaAC,MAAM;eAANA;;;AA5BT,SAASL,cAAiBM,KAAU,EAAEC,SAA+B;IAC1E,IAAK,IAAIC,IAAIF,MAAMG,MAAM,GAAG,GAAGD,KAAK,GAAGA,IAAK;QAC1C,IAAID,UAAUD,KAAK,CAACE,EAAE,GAAG;YACvB,OAAOA;QACT;IACF;IACA,OAAO,CAAC;AACV;AAGO,SAASN,aAAgBQ,CAAM,EAAEC,CAAM;IAC5C,MAAM,CAACC,GAAGC,EAAE,GAAGH,EAAED,MAAM,GAAGE,EAAEF,MAAM,GAAG;QAACC;QAAGC;KAAE,GAAG;QAACA;QAAGD;KAAE;IACpD,OAAOE,EAAEE,MAAM,CAAC,CAACC,QAAUF,EAAEG,QAAQ,CAACD;AACxC;AAEO,SAASX,aAAgBa,MAAW,EAAEC,QAAW,EAAEC,WAAc;IACtE,MAAMC,QAAQH,OAAOI,OAAO,CAACH;IAC7B,IAAIE,QAAQ,CAAC,GAAG;QACdH,MAAM,CAACG,MAAM,GAAGD;IAClB;IACA,OAAOF;AACT;AAEO,SAASd,iBAAoBc,MAAW,EAAEC,QAAW,EAAEC,WAAc;IAC1E,OAAOF,OAAOK,GAAG,CAAC,CAACP,QAAWA,UAAUG,WAAWC,cAAcJ;AACnE;AAGO,SAASV,OAAUC,KAAU,EAAEiB,GAAwB;IAC5D,MAAMC,OAAmC,CAAC;IAC1C,OAAOlB,MAAMQ,MAAM,CAAC,CAACW;QACnB,MAAMC,IAAIH,IAAIE;QACd,IAAID,IAAI,CAACE,EAAE,EAAE;YACX,OAAO;QACT;QACAF,IAAI,CAACE,EAAE,GAAG;QACV,OAAO;IACT;AACF;AAGO,SAAS3B,MAASO,KAAU,EAAEqB,IAAY;IAC/C,MAAMC,UAAU,EAAE;IAClB,IAAIR,QAAQ;IACZ,MAAOA,QAAQd,MAAMG,MAAM,CAAE;QAC3BmB,QAAQC,IAAI,CAACvB,MAAMwB,KAAK,CAACV,OAAQA,SAASO;IAC5C;IACA,OAAOC;AACT;AAGO,SAAS3B,QAAgC8B,IAAS,EAAEC,MAAsB;IAC/E,OAAOD,KAAKE,MAAM,CAChB,CAACC,UAAUC;QACT,MAAMC,QAAQJ,OAAOG;QACrB,IAAI,CAACD,QAAQ,CAACE,MAAM,EAAE;YACpBF,QAAQ,CAACE,MAAM,GAAG,EAAE;QACtB;QACAF,QAAQ,CAACE,MAAM,CAACP,IAAI,CAACM;QACrB,OAAOD;IACT,GACA,CAAC;AAEL"}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
Object.defineProperty(exports, "testPortAsync", {
|
|
6
|
+
enumerable: true,
|
|
7
|
+
get: function() {
|
|
8
|
+
return testPortAsync;
|
|
9
|
+
}
|
|
10
|
+
});
|
|
11
|
+
function _nodenet() {
|
|
12
|
+
const data = /*#__PURE__*/ _interop_require_default(require("node:net"));
|
|
13
|
+
_nodenet = function() {
|
|
14
|
+
return data;
|
|
15
|
+
};
|
|
16
|
+
return data;
|
|
17
|
+
}
|
|
18
|
+
function _interop_require_default(obj) {
|
|
19
|
+
return obj && obj.__esModule ? obj : {
|
|
20
|
+
default: obj
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
async function testHostPortAsync(port, host) {
|
|
24
|
+
return new Promise((resolve)=>{
|
|
25
|
+
const server = _nodenet().default.createServer();
|
|
26
|
+
server.listen({
|
|
27
|
+
port,
|
|
28
|
+
host
|
|
29
|
+
}, ()=>{
|
|
30
|
+
server.once('close', ()=>{
|
|
31
|
+
setTimeout(()=>resolve(true), 0);
|
|
32
|
+
});
|
|
33
|
+
server.close();
|
|
34
|
+
});
|
|
35
|
+
server.once('error', (_error)=>{
|
|
36
|
+
setTimeout(()=>resolve(false), 0);
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
async function testPortAsync(port, hostnames) {
|
|
41
|
+
if (!(hostnames == null ? void 0 : hostnames.length)) {
|
|
42
|
+
hostnames = [
|
|
43
|
+
null
|
|
44
|
+
];
|
|
45
|
+
}
|
|
46
|
+
for (const host of hostnames){
|
|
47
|
+
if (!await testHostPortAsync(port, host)) {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return port;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
//# sourceMappingURL=freeport.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/utils/freeport.ts"],"sourcesContent":["import net from 'node:net';\n\nasync function testHostPortAsync(port: number, host: string | null): Promise<boolean> {\n return new Promise((resolve) => {\n const server = net.createServer();\n server.listen({ port, host }, () => {\n server.once('close', () => {\n setTimeout(() => resolve(true), 0);\n });\n server.close();\n });\n server.once('error', (_error) => {\n setTimeout(() => resolve(false), 0);\n });\n });\n}\n\nexport async function testPortAsync(\n port: number,\n hostnames?: (string | null)[]\n): Promise<number | null> {\n if (!hostnames?.length) {\n hostnames = [null];\n }\n for (const host of hostnames) {\n if (!(await testHostPortAsync(port, host))) {\n return null;\n }\n }\n return port;\n}\n"],"names":["testPortAsync","testHostPortAsync","port","host","Promise","resolve","server","net","createServer","listen","once","setTimeout","close","_error","hostnames","length"],"mappings":";;;;+BAiBsBA;;;eAAAA;;;;gEAjBN;;;;;;;;;;;AAEhB,eAAeC,kBAAkBC,IAAY,EAAEC,IAAmB;IAChE,OAAO,IAAIC,QAAQ,CAACC;QAClB,MAAMC,SAASC,kBAAG,CAACC,YAAY;QAC/BF,OAAOG,MAAM,CAAC;YAAEP;YAAMC;QAAK,GAAG;YAC5BG,OAAOI,IAAI,CAAC,SAAS;gBACnBC,WAAW,IAAMN,QAAQ,OAAO;YAClC;YACAC,OAAOM,KAAK;QACd;QACAN,OAAOI,IAAI,CAAC,SAAS,CAACG;YACpBF,WAAW,IAAMN,QAAQ,QAAQ;QACnC;IACF;AACF;AAEO,eAAeL,cACpBE,IAAY,EACZY,SAA6B;IAE7B,IAAI,EAACA,6BAAAA,UAAWC,MAAM,GAAE;QACtBD,YAAY;YAAC;SAAK;IACpB;IACA,KAAK,MAAMX,QAAQW,UAAW;QAC5B,IAAI,CAAE,MAAMb,kBAAkBC,MAAMC,OAAQ;YAC1C,OAAO;QACT;IACF;IACA,OAAOD;AACT"}
|
package/build/src/utils/port.js
CHANGED
|
@@ -29,15 +29,9 @@ function _chalk() {
|
|
|
29
29
|
};
|
|
30
30
|
return data;
|
|
31
31
|
}
|
|
32
|
-
function _freeportasync() {
|
|
33
|
-
const data = /*#__PURE__*/ _interop_require_default(require("freeport-async"));
|
|
34
|
-
_freeportasync = function() {
|
|
35
|
-
return data;
|
|
36
|
-
};
|
|
37
|
-
return data;
|
|
38
|
-
}
|
|
39
32
|
const _env = require("./env");
|
|
40
33
|
const _errors = require("./errors");
|
|
34
|
+
const _freeport = require("./freeport");
|
|
41
35
|
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../log"));
|
|
42
36
|
function _interop_require_default(obj) {
|
|
43
37
|
return obj && obj.__esModule ? obj : {
|
|
@@ -86,23 +80,19 @@ function _interop_require_wildcard(obj, nodeInterop) {
|
|
|
86
80
|
return newObj;
|
|
87
81
|
}
|
|
88
82
|
async function getFreePortAsync(rangeStart) {
|
|
89
|
-
const port = await (0,
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
]
|
|
94
|
-
});
|
|
83
|
+
const port = await (0, _freeport.testPortAsync)(rangeStart, [
|
|
84
|
+
null,
|
|
85
|
+
'localhost'
|
|
86
|
+
]);
|
|
95
87
|
if (!port) {
|
|
96
88
|
throw new _errors.CommandError('NO_PORT_FOUND', 'No available port found');
|
|
97
89
|
}
|
|
98
90
|
return port;
|
|
99
91
|
}
|
|
100
92
|
async function ensurePortAvailabilityAsync(projectRoot, { port }) {
|
|
101
|
-
const freePort = await (0,
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
]
|
|
105
|
-
});
|
|
93
|
+
const freePort = await (0, _freeport.testPortAsync)(port, [
|
|
94
|
+
null
|
|
95
|
+
]);
|
|
106
96
|
// Check if port has become busy during the build.
|
|
107
97
|
if (freePort === port) {
|
|
108
98
|
return true;
|
|
@@ -138,15 +128,13 @@ async function isBusyPortRunningSameProcessAsync(projectRoot, { port }) {
|
|
|
138
128
|
}
|
|
139
129
|
async function choosePortAsync(projectRoot, { defaultPort, host, reuseExistingPort }) {
|
|
140
130
|
try {
|
|
141
|
-
const port = await (0,
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
]
|
|
145
|
-
});
|
|
131
|
+
const port = await (0, _freeport.testPortAsync)(defaultPort, [
|
|
132
|
+
host ?? null
|
|
133
|
+
]);
|
|
146
134
|
if (port === defaultPort || defaultPort === 0) {
|
|
147
135
|
return port;
|
|
148
136
|
}
|
|
149
|
-
const isRestricted = isRestrictedPort(port);
|
|
137
|
+
const isRestricted = port && isRestrictedPort(port);
|
|
150
138
|
let message = isRestricted ? `Admin permissions are required to run a server on a port below 1024` : `Port ${_chalk().default.bold(defaultPort)} is`;
|
|
151
139
|
const { getRunningProcess } = require('./getRunningProcess');
|
|
152
140
|
const runningProcess = isRestricted ? null : getRunningProcess(defaultPort);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/port.ts"],"sourcesContent":["import chalk from 'chalk';\nimport
|
|
1
|
+
{"version":3,"sources":["../../../src/utils/port.ts"],"sourcesContent":["import chalk from 'chalk';\n\nimport { env } from './env';\nimport { CommandError } from './errors';\nimport { testPortAsync } from './freeport';\nimport * as Log from '../log';\n\n/** Get a free port or assert a CLI command error. */\nexport async function getFreePortAsync(rangeStart: number): Promise<number> {\n const port = await testPortAsync(rangeStart, [null, 'localhost']);\n if (!port) {\n throw new CommandError('NO_PORT_FOUND', 'No available port found');\n }\n\n return port;\n}\n\n/** @return `true` if the port can still be used to start the dev server, `false` if the dev server should be skipped, and asserts if the port is now taken. */\nexport async function ensurePortAvailabilityAsync(\n projectRoot: string,\n { port }: { port: number }\n): Promise<boolean> {\n const freePort = await testPortAsync(port, [null]);\n // Check if port has become busy during the build.\n if (freePort === port) {\n return true;\n }\n\n const isBusy = await isBusyPortRunningSameProcessAsync(projectRoot, { port });\n if (!isBusy) {\n throw new CommandError(\n `Port \"${port}\" became busy running another process while the app was compiling. Re-run command to use a new port.`\n );\n }\n\n // Log that the dev server will not be started and that the logs will appear in another window.\n Log.log(\n '› The dev server for this app is already running in another window. Logs will appear there.'\n );\n return false;\n}\n\nfunction isRestrictedPort(port: number) {\n if (process.platform !== 'win32' && port < 1024) {\n const isRoot = process.getuid && process.getuid() === 0;\n return !isRoot;\n }\n return false;\n}\n\nasync function isBusyPortRunningSameProcessAsync(projectRoot: string, { port }: { port: number }) {\n const { getRunningProcess } =\n require('./getRunningProcess') as typeof import('./getRunningProcess');\n\n const runningProcess = isRestrictedPort(port) ? null : getRunningProcess(port);\n if (runningProcess) {\n if (runningProcess.directory === projectRoot) {\n return true;\n } else {\n return false;\n }\n }\n\n return null;\n}\n\n// TODO(Bacon): Revisit after all start and run code is merged.\nexport async function choosePortAsync(\n projectRoot: string,\n {\n defaultPort,\n host,\n reuseExistingPort,\n }: {\n defaultPort: number;\n host?: string;\n reuseExistingPort?: boolean;\n }\n): Promise<number | null> {\n try {\n const port = await testPortAsync(defaultPort, [host ?? null]);\n if (port === defaultPort || defaultPort === 0) {\n return port;\n }\n\n const isRestricted = port && isRestrictedPort(port);\n\n let message = isRestricted\n ? `Admin permissions are required to run a server on a port below 1024`\n : `Port ${chalk.bold(defaultPort)} is`;\n\n const { getRunningProcess } =\n require('./getRunningProcess') as typeof import('./getRunningProcess');\n const runningProcess = isRestricted ? null : getRunningProcess(defaultPort);\n\n if (runningProcess) {\n const pidTag = chalk.gray(`(pid ${runningProcess.pid})`);\n if (runningProcess.directory === projectRoot) {\n message += ` running this app in another window`;\n if (reuseExistingPort) {\n return null;\n }\n } else {\n message += ` running ${chalk.cyan(runningProcess.command)} in another window`;\n }\n message += '\\n' + chalk.gray(` ${runningProcess.directory} ${pidTag}`);\n } else {\n message += ' being used by another process';\n }\n\n Log.log(`\\u203A ${message}`);\n const { confirmAsync } = require('./prompts') as typeof import('./prompts');\n const change = await confirmAsync({\n message: `Use port ${port} instead?`,\n initial: true,\n });\n return change ? port : null;\n } catch (error: any) {\n if (error.code === 'ABORTED') {\n throw error;\n } else if (error.code === 'NON_INTERACTIVE') {\n Log.warn(chalk.yellow(error.message));\n return null;\n }\n throw error;\n }\n}\n\n// TODO(Bacon): Revisit after all start and run code is merged.\nexport async function resolvePortAsync(\n projectRoot: string,\n {\n /** Should opt to reuse a port that is running the same project in another window. */\n reuseExistingPort,\n /** Preferred port. */\n defaultPort,\n /** Backup port for when the default isn't available. */\n fallbackPort,\n }: {\n reuseExistingPort?: boolean;\n defaultPort?: string | number;\n fallbackPort?: number;\n } = {}\n): Promise<number | null> {\n let port: number;\n if (typeof defaultPort === 'string') {\n port = parseInt(defaultPort, 10);\n } else if (typeof defaultPort === 'number') {\n port = defaultPort;\n } else {\n port = env.RCT_METRO_PORT || fallbackPort || 8081;\n }\n\n // Only check the port when the bundler is running.\n const resolvedPort = await choosePortAsync(projectRoot, {\n defaultPort: port,\n reuseExistingPort,\n });\n if (resolvedPort == null) {\n Log.log('\\u203A Skipping dev server');\n // Skip bundling if the port is null\n } else {\n // Use the new or resolved port\n process.env.RCT_METRO_PORT = String(resolvedPort);\n }\n\n return resolvedPort;\n}\n"],"names":["choosePortAsync","ensurePortAvailabilityAsync","getFreePortAsync","resolvePortAsync","rangeStart","port","testPortAsync","CommandError","projectRoot","freePort","isBusy","isBusyPortRunningSameProcessAsync","Log","log","isRestrictedPort","process","platform","isRoot","getuid","getRunningProcess","require","runningProcess","directory","defaultPort","host","reuseExistingPort","isRestricted","message","chalk","bold","pidTag","gray","pid","cyan","command","confirmAsync","change","initial","error","code","warn","yellow","fallbackPort","parseInt","env","RCT_METRO_PORT","resolvedPort","String"],"mappings":";;;;;;;;;;;IAmEsBA,eAAe;eAAfA;;IAjDAC,2BAA2B;eAA3BA;;IAVAC,gBAAgB;eAAhBA;;IAyHAC,gBAAgB;eAAhBA;;;;gEAjIJ;;;;;;qBAEE;wBACS;0BACC;6DACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGd,eAAeD,iBAAiBE,UAAkB;IACvD,MAAMC,OAAO,MAAMC,IAAAA,uBAAa,EAACF,YAAY;QAAC;QAAM;KAAY;IAChE,IAAI,CAACC,MAAM;QACT,MAAM,IAAIE,oBAAY,CAAC,iBAAiB;IAC1C;IAEA,OAAOF;AACT;AAGO,eAAeJ,4BACpBO,WAAmB,EACnB,EAAEH,IAAI,EAAoB;IAE1B,MAAMI,WAAW,MAAMH,IAAAA,uBAAa,EAACD,MAAM;QAAC;KAAK;IACjD,kDAAkD;IAClD,IAAII,aAAaJ,MAAM;QACrB,OAAO;IACT;IAEA,MAAMK,SAAS,MAAMC,kCAAkCH,aAAa;QAAEH;IAAK;IAC3E,IAAI,CAACK,QAAQ;QACX,MAAM,IAAIH,oBAAY,CACpB,CAAC,MAAM,EAAEF,KAAK,oGAAoG,CAAC;IAEvH;IAEA,+FAA+F;IAC/FO,KAAIC,GAAG,CACL;IAEF,OAAO;AACT;AAEA,SAASC,iBAAiBT,IAAY;IACpC,IAAIU,QAAQC,QAAQ,KAAK,W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|
|
|
33
33
|
});
|
|
34
34
|
const _array = require("./array");
|
|
35
35
|
const _errors = require("./errors");
|
|
36
|
+
/** Convert ExtraArgsSpec to arg.Spec (for validation) and extract allowedValues */ function parseExtraArgMap(extraArgMap) {
|
|
37
|
+
const spec = {};
|
|
38
|
+
const allowedValues = {};
|
|
39
|
+
for (const [key, value] of Object.entries(extraArgMap)){
|
|
40
|
+
if (typeof value === 'string') {
|
|
41
|
+
// Alias (e.g. '-f': '--flag')
|
|
42
|
+
spec[key] = value;
|
|
43
|
+
} else if (Array.isArray(value)) {
|
|
44
|
+
// Tuple [Boolean, ...strings] - Boolean is enforced by the type, but check at runtime too
|
|
45
|
+
const [first, ...stringValues] = value;
|
|
46
|
+
if (first !== Boolean) {
|
|
47
|
+
throw new _errors.CommandError('BAD_ARGS', `Invalid extraArgMap spec for ${key}: first element must be Boolean`);
|
|
48
|
+
}
|
|
49
|
+
spec[key] = Boolean;
|
|
50
|
+
allowedValues[key] = [
|
|
51
|
+
'true',
|
|
52
|
+
'false',
|
|
53
|
+
...stringValues
|
|
54
|
+
];
|
|
55
|
+
} else {
|
|
56
|
+
// Boolean - any value allowed
|
|
57
|
+
spec[key] = Boolean;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
spec,
|
|
62
|
+
allowedValues
|
|
63
|
+
};
|
|
64
|
+
}
|
|
36
65
|
/** Split up arguments that are formatted like `--foo=bar` or `-f="bar"` to `['--foo', 'bar']` */ function splitArgs(args) {
|
|
37
66
|
const result = [];
|
|
38
67
|
for (const arg of args){
|
|
@@ -48,27 +77,31 @@ const _errors = require("./errors");
|
|
|
48
77
|
}
|
|
49
78
|
return result;
|
|
50
79
|
}
|
|
51
|
-
async function resolveStringOrBooleanArgsAsync(
|
|
52
|
-
args = splitArgs(
|
|
80
|
+
async function resolveStringOrBooleanArgsAsync(argv, rawArgMap, extraArgMap) {
|
|
81
|
+
let args = splitArgs(argv);
|
|
82
|
+
const { spec: extraArgSpec, allowedValues } = parseExtraArgMap(extraArgMap);
|
|
83
|
+
const combinedSpec = {
|
|
84
|
+
...rawArgMap,
|
|
85
|
+
...extraArgSpec
|
|
86
|
+
};
|
|
53
87
|
// Assert any missing arguments
|
|
54
|
-
assertUnknownArgs(
|
|
55
|
-
...rawMap,
|
|
56
|
-
...extraArgs
|
|
57
|
-
}, args);
|
|
88
|
+
assertUnknownArgs(combinedSpec, args);
|
|
58
89
|
// Collapse aliases into fully qualified arguments.
|
|
59
|
-
args = collapseAliases(
|
|
90
|
+
args = collapseAliases(combinedSpec, args);
|
|
91
|
+
// Filter out array-type arguments so _resolveStringOrBooleanArgs can process the rest.
|
|
92
|
+
// This is necessary because _resolveStringOrBooleanArgs can't handle array-type args like --platform.
|
|
93
|
+
const filteredArgs = filterOutArrayArgs(args, combinedSpec);
|
|
60
94
|
// Resolve all of the string or boolean arguments and the project root.
|
|
61
|
-
return _resolveStringOrBooleanArgs(
|
|
62
|
-
...rawMap,
|
|
63
|
-
...extraArgs
|
|
64
|
-
}, args);
|
|
95
|
+
return _resolveStringOrBooleanArgs(combinedSpec, filteredArgs, allowedValues);
|
|
65
96
|
}
|
|
66
|
-
async function resolveCustomBooleanArgsAsync(
|
|
67
|
-
const results = await resolveStringOrBooleanArgsAsync(
|
|
97
|
+
async function resolveCustomBooleanArgsAsync(argv, rawArgMap, extraArgMap) {
|
|
98
|
+
const results = await resolveStringOrBooleanArgsAsync(argv, rawArgMap, extraArgMap);
|
|
68
99
|
return {
|
|
69
100
|
...results,
|
|
70
101
|
args: Object.fromEntries(Object.entries(results.args).map(([key, value])=>{
|
|
71
|
-
|
|
102
|
+
// Skip aliases (e.g. '-f': '--flag') - only process actual flags
|
|
103
|
+
const extraArgValue = extraArgMap[key];
|
|
104
|
+
if (extraArgValue && typeof extraArgValue !== 'string') {
|
|
72
105
|
if (typeof value === 'string') {
|
|
73
106
|
if (![
|
|
74
107
|
'true',
|
|
@@ -89,13 +122,20 @@ async function resolveCustomBooleanArgsAsync(args, rawMap, extraArgs) {
|
|
|
89
122
|
}))
|
|
90
123
|
};
|
|
91
124
|
}
|
|
92
|
-
function _resolveStringOrBooleanArgs(arg, args) {
|
|
125
|
+
function _resolveStringOrBooleanArgs(arg, args, allowedValues) {
|
|
93
126
|
// Default project root, if a custom one is defined then it will overwrite this.
|
|
94
127
|
let projectRoot = '.';
|
|
95
128
|
// The resolved arguments.
|
|
96
129
|
const settings = {};
|
|
97
130
|
// Create a list of possible arguments, this will filter out aliases.
|
|
98
131
|
const possibleArgs = Object.entries(arg).filter(([, value])=>typeof value !== 'string').map(([key])=>key);
|
|
132
|
+
// Check if a value is allowed for a given flag
|
|
133
|
+
const isAllowedValue = (flag, value)=>{
|
|
134
|
+
if (!allowedValues || !allowedValues[flag]) {
|
|
135
|
+
return true; // No restrictions, allow any value
|
|
136
|
+
}
|
|
137
|
+
return allowedValues[flag].includes(value);
|
|
138
|
+
};
|
|
99
139
|
// Loop over arguments in reverse order so we can resolve if a value belongs to a flag.
|
|
100
140
|
for(let i = args.length - 1; i > -1; i--){
|
|
101
141
|
const value = args[i];
|
|
@@ -110,7 +150,7 @@ function _resolveStringOrBooleanArgs(arg, args) {
|
|
|
110
150
|
} else {
|
|
111
151
|
// Get the previous argument in the array.
|
|
112
152
|
const nextValue = i > 0 ? args[i - 1] : null;
|
|
113
|
-
if (nextValue && possibleArgs.includes(nextValue)) {
|
|
153
|
+
if (nextValue && possibleArgs.includes(nextValue) && isAllowedValue(nextValue, value)) {
|
|
114
154
|
// We don't override arguments that are already set
|
|
115
155
|
if (!(nextValue in settings)) {
|
|
116
156
|
settings[nextValue] = value;
|
|
@@ -134,10 +174,11 @@ function _resolveStringOrBooleanArgs(arg, args) {
|
|
|
134
174
|
function collapseAliases(arg, args) {
|
|
135
175
|
const aliasMap = getAliasTuples(arg);
|
|
136
176
|
for (const [arg, alias] of aliasMap){
|
|
137
|
-
args = (0, _array.
|
|
177
|
+
args = (0, _array.replaceAllValues)(args, arg, alias);
|
|
138
178
|
}
|
|
139
179
|
// Assert if there are duplicate flags after we collapse the aliases.
|
|
140
|
-
|
|
180
|
+
// Skip array-type arguments (like --platform) which can have multiple values.
|
|
181
|
+
assertDuplicateArgs(args, aliasMap, arg);
|
|
141
182
|
return args;
|
|
142
183
|
}
|
|
143
184
|
function assertUnknownArgs(arg, args) {
|
|
@@ -150,8 +191,34 @@ function assertUnknownArgs(arg, args) {
|
|
|
150
191
|
function getAliasTuples(arg) {
|
|
151
192
|
return Object.entries(arg).filter(([, value])=>typeof value === 'string');
|
|
152
193
|
}
|
|
153
|
-
|
|
194
|
+
/** Filter out array-type arguments from the spec (and their values).
|
|
195
|
+
* This is needed because _resolveStringOrBooleanArgs can't handle array args like --platform.
|
|
196
|
+
*/ function filterOutArrayArgs(args, spec) {
|
|
197
|
+
// Get the set of flag names that are array types
|
|
198
|
+
const arrayFlags = new Set(Object.entries(spec).filter(([, value])=>Array.isArray(value)).map(([key])=>key));
|
|
199
|
+
if (arrayFlags.size === 0) {
|
|
200
|
+
return args;
|
|
201
|
+
}
|
|
202
|
+
const result = [];
|
|
203
|
+
for(let i = 0; i < args.length; i++){
|
|
204
|
+
const arg = args[i];
|
|
205
|
+
if (arrayFlags.has(arg)) {
|
|
206
|
+
// Skip this flag and its value if it has one
|
|
207
|
+
if (i + 1 < args.length && !args[i + 1].startsWith('-')) {
|
|
208
|
+
i++;
|
|
209
|
+
}
|
|
210
|
+
} else {
|
|
211
|
+
result.push(arg);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return result;
|
|
215
|
+
}
|
|
216
|
+
function assertDuplicateArgs(args, argNameAliasTuple, spec) {
|
|
154
217
|
for (const [argName, argNameAlias] of argNameAliasTuple){
|
|
218
|
+
// Skip array-type arguments (like --platform) which can have multiple values
|
|
219
|
+
if (spec && Array.isArray(spec[argNameAlias])) {
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
155
222
|
if (args.filter((a)=>[
|
|
156
223
|
argName,
|
|
157
224
|
argNameAlias
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/resolveArgs.ts"],"sourcesContent":["import arg, { Spec } from 'arg';\n\nimport { replaceValue } from './array';\nimport { CommandError } from './errors';\n\n/** Split up arguments that are formatted like `--foo=bar` or `-f=\"bar\"` to `['--foo', 'bar']` */\nfunction splitArgs(args: string[]): string[] {\n const result: string[] = [];\n\n for (const arg of args) {\n if (arg.startsWith('-')) {\n const [key, ...props] = arg.split('=');\n result.push(key);\n if (props.length) {\n result.push(props.join('='));\n }\n } else {\n result.push(arg);\n }\n }\n\n return result;\n}\n\n/**\n * Enables the resolution of arguments that can either be a string or a boolean.\n *\n * @param args arguments that were passed to the command.\n * @param rawMap raw map of arguments that are passed to the command.\n * @param extraArgs extra arguments and aliases that should be resolved as string or boolean.\n * @returns parsed arguments and project root.\n */\nexport async function resolveStringOrBooleanArgsAsync(\n args: string[],\n rawMap: arg.Spec,\n extraArgs: arg.Spec\n) {\n args = splitArgs(args);\n\n // Assert any missing arguments\n assertUnknownArgs(\n {\n ...rawMap,\n ...extraArgs,\n },\n args\n );\n\n // Collapse aliases into fully qualified arguments.\n args = collapseAliases(extraArgs, args);\n\n // Resolve all of the string or boolean arguments and the project root.\n return _resolveStringOrBooleanArgs({ ...rawMap, ...extraArgs }, args);\n}\n\n/**\n * Enables the resolution of boolean arguments that can be formatted like `--foo=true` or `--foo false`\n *\n * @param args arguments that were passed to the command.\n * @param rawMap raw map of arguments that are passed to the command.\n * @param extraArgs extra arguments and aliases that should be resolved as string or boolean.\n * @returns parsed arguments and project root.\n */\nexport async function resolveCustomBooleanArgsAsync(\n args: string[],\n rawMap: arg.Spec,\n extraArgs: arg.Spec\n) {\n const results = await resolveStringOrBooleanArgsAsync(args, rawMap, extraArgs);\n\n return {\n ...results,\n args: Object.fromEntries(\n Object.entries(results.args).map(([key, value]) => {\n if (extraArgs[key]) {\n if (typeof value === 'string') {\n if (!['true', 'false'].includes(value)) {\n throw new CommandError(\n 'BAD_ARGS',\n `Invalid boolean argument: ${key}=${value}. Expected one of: true, false`\n );\n }\n return [key, value === 'true'];\n }\n }\n return [key, value];\n })\n ),\n };\n}\n\nexport function _resolveStringOrBooleanArgs(arg: Spec, args: string[]) {\n // Default project root, if a custom one is defined then it will overwrite this.\n let projectRoot: string = '.';\n // The resolved arguments.\n const settings: Record<string, string | boolean | undefined> = {};\n\n // Create a list of possible arguments, this will filter out aliases.\n const possibleArgs = Object.entries(arg)\n .filter(([, value]) => typeof value !== 'string')\n .map(([key]) => key);\n\n // Loop over arguments in reverse order so we can resolve if a value belongs to a flag.\n for (let i = args.length - 1; i > -1; i--) {\n const value = args[i];\n // At this point we should have converted all aliases to fully qualified arguments.\n if (value.startsWith('--')) {\n // If we ever find an argument then it must be a boolean because we are checking in reverse\n // and removing arguments from the array if we find a string.\n // We don't override arguments that are already set\n if (!(value in settings)) {\n settings[value] = true;\n }\n } else {\n // Get the previous argument in the array.\n const nextValue = i > 0 ? args[i - 1] : null;\n if (nextValue && possibleArgs.includes(nextValue)) {\n // We don't override arguments that are already set\n if (!(nextValue in settings)) {\n settings[nextValue] = value;\n }\n i--;\n } else if (\n // If the last value is not a flag and it doesn't have a recognized flag before it (instead having a string value or nothing)\n // then it must be the project root.\n i ===\n args.length - 1\n ) {\n projectRoot = value;\n } else {\n // This will asserts if two strings are passed in a row and not at the end of the line.\n throw new CommandError('BAD_ARGS', `Unknown argument: ${value}`);\n }\n }\n }\n\n return {\n args: settings,\n projectRoot,\n };\n}\n\n/** Convert all aliases to fully qualified flag names. */\nexport function collapseAliases(arg: Spec, args: string[]): string[] {\n const aliasMap = getAliasTuples(arg);\n\n for (const [arg, alias] of aliasMap) {\n args = replaceValue(args, arg, alias);\n }\n\n // Assert if there are duplicate flags after we collapse the aliases.\n assertDuplicateArgs(args, aliasMap);\n return args;\n}\n\n/** Assert that the spec has unknown arguments. */\nexport function assertUnknownArgs(arg: Spec, args: string[]) {\n const allowedArgs = Object.keys(arg);\n const unknownArgs = args.filter((arg) => !allowedArgs.includes(arg) && arg.startsWith('-'));\n if (unknownArgs.length > 0) {\n throw new CommandError(`Unknown arguments: ${unknownArgs.join(', ')}`);\n }\n}\n\nfunction getAliasTuples(arg: Spec): [string, string][] {\n return Object.entries(arg).filter(([, value]) => typeof value === 'string') as [string, string][];\n}\n\n/** Asserts that a duplicate flag has been used, this naively throws without knowing if an alias or flag were used as the duplicate. */\nexport function assertDuplicateArgs(args: string[], argNameAliasTuple: [string, string][]) {\n for (const [argName, argNameAlias] of argNameAliasTuple) {\n if (args.filter((a) => [argName, argNameAlias].includes(a)).length > 1) {\n throw new CommandError(\n 'BAD_ARGS',\n `Can only provide one instance of ${argName} or ${argNameAlias}`\n );\n }\n }\n}\n\nexport function assertNonBooleanArg(argName: string, arg: any): asserts arg is string | string[] {\n if (arg == null || typeof arg === 'boolean') {\n throw new CommandError('BAD_ARGS', `Expected input for arg ${argName}`);\n }\n}\n"],"names":["_resolveStringOrBooleanArgs","assertDuplicateArgs","assertNonBooleanArg","assertUnknownArgs","collapseAliases","resolveCustomBooleanArgsAsync","resolveStringOrBooleanArgsAsync","splitArgs","args","result","arg","startsWith","key","props","split","push","length","join","rawMap","extraArgs","results","Object","fromEntries","entries","map","value","includes","CommandError","projectRoot","settings","possibleArgs","filter","i","nextValue","aliasMap","getAliasTuples","alias","replaceValue","allowedArgs","keys","unknownArgs","argNameAliasTuple","argName","argNameAlias","a"],"mappings":";;;;;;;;;;;IA2FgBA,2BAA2B;eAA3BA;;IA8EAC,mBAAmB;eAAnBA;;IAWAC,mBAAmB;eAAnBA;;IAxBAC,iBAAiB;eAAjBA;;IAbAC,eAAe;eAAfA;;IAhFMC,6BAA6B;eAA7BA;;IA/BAC,+BAA+B;eAA/BA;;;uBA9BO;wBACA;AAE7B,+FAA+F,GAC/F,SAASC,UAAUC,IAAc;IAC/B,MAAMC,SAAmB,EAAE;IAE3B,KAAK,MAAMC,OAAOF,KAAM;QACtB,IAAIE,IAAIC,UAAU,CAAC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BAAoBO,MAAM0B;IAC1B,OAAO1B;AACT;AAGO,SAASL,kBAAkBO,GAAS,EAAEF,IAAc;IACzD,MAAM8B,cAAcjB,OAAOkB,IAAI,CAAC7B;IAChC,MAAM8B,cAAchC,KAAKuB,MAAM,CAAC,CAACrB,MAAQ,CAAC4B,YAAYZ,QAAQ,CAAChB,QAAQA,IAAIC,UAAU,CAAC;IACtF,IAAI6B,YAAYxB,MAAM,GAAG,GAAG;QAC1B,MAAM,IAAIW,oBAAY,CAAC,CAAC,mBAAmB,EAAEa,YAAYvB,IAAI,CAAC,OAAO;IACvE;AACF;AAEA,SAASkB,eAAezB,GAAS;IAC/B,OAAOW,OAAOE,OAAO,CAACb,KAAKqB,MAAM,CAAC,CAAC,GAAGN,MAAM,GAAK,OAAOA,UAAU;AACpE;AAGO,SAASxB,oBAAoBO,IAAc,EAAEiC,iBAAqC;IACvF,KAAK,MAAM,CAACC,SAASC,aAAa,IAAIF,kBAAmB;QACvD,IAAIjC,KAAKuB,MAAM,CAAC,CAACa,IAAM;gBAACF;gBAASC;aAAa,CAACjB,QAAQ,CAACkB,IAAI5B,MAAM,GAAG,GAAG;YACtE,MAAM,IAAIW,oBAAY,CACpB,YACA,CAAC,iCAAiC,EAAEe,QAAQ,IAAI,EAAEC,cAAc;QAEpE;IACF;AACF;AAEO,SAASzC,oBAAoBwC,OAAe,EAAEhC,GAAQ;IAC3D,IAAIA,OAAO,QAAQ,OAAOA,QAAQ,WAAW;QAC3C,MAAM,IAAIiB,oBAAY,CAAC,YAAY,CAAC,uBAAuB,EAAEe,SAAS;IACxE;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/utils/resolveArgs.ts"],"sourcesContent":["import arg, { Spec } from 'arg';\n\nimport { replaceAllValues } from './array';\nimport { CommandError } from './errors';\n\n/**\n * Spec for extra arguments that can be string or boolean.\n * - `'--flag': Boolean` → accepts any value\n * - `'--flag': [Boolean, 'a', 'b']` → restricted to 'true', 'false', 'a', 'b'\n * - `'-f': '--flag'` → alias\n */\nexport type ExtraArgsSpec = Record<string, typeof Boolean | string | [typeof Boolean, ...string[]]>;\n\n/** Convert ExtraArgsSpec to arg.Spec (for validation) and extract allowedValues */\nfunction parseExtraArgMap(extraArgMap: ExtraArgsSpec): {\n spec: arg.Spec;\n allowedValues: Record<string, string[]>;\n} {\n const spec: arg.Spec = {};\n const allowedValues: Record<string, string[]> = {};\n\n for (const [key, value] of Object.entries(extraArgMap)) {\n if (typeof value === 'string') {\n // Alias (e.g. '-f': '--flag')\n spec[key] = value;\n } else if (Array.isArray(value)) {\n // Tuple [Boolean, ...strings] - Boolean is enforced by the type, but check at runtime too\n const [first, ...stringValues] = value;\n if (first !== Boolean) {\n throw new CommandError(\n 'BAD_ARGS',\n `Invalid extraArgMap spec for ${key}: first element must be Boolean`\n );\n }\n spec[key] = Boolean;\n allowedValues[key] = ['true', 'false', ...stringValues];\n } else {\n // Boolean - any value allowed\n spec[key] = Boolean;\n }\n }\n\n return { spec, allowedValues };\n}\n\n/** Split up arguments that are formatted like `--foo=bar` or `-f=\"bar\"` to `['--foo', 'bar']` */\nfunction splitArgs(args: string[]): string[] {\n const result: string[] = [];\n\n for (const arg of args) {\n if (arg.startsWith('-')) {\n const [key, ...props] = arg.split('=');\n result.push(key);\n if (props.length) {\n result.push(props.join('='));\n }\n } else {\n result.push(arg);\n }\n }\n\n return result;\n}\n\n/**\n * Enables the resolution of arguments that can either be a string or a boolean.\n *\n * @param argv arguments that were passed to the command.\n * @param rawArgMap base argument spec defining valid arguments and their types.\n * @param extraArgMap extra arguments and aliases that should be resolved as string or boolean.\n * - `'--flag': Boolean` → accepts any value\n * - `'--flag': [Boolean, 'a', 'b']` → restricted to 'true', 'false', 'a', 'b'\n * - `'-f': '--flag'` → alias\n * @returns parsed arguments and project root.\n */\nexport async function resolveStringOrBooleanArgsAsync(\n argv: string[],\n rawArgMap: arg.Spec,\n extraArgMap: ExtraArgsSpec\n) {\n let args = splitArgs(argv);\n\n const { spec: extraArgSpec, allowedValues } = parseExtraArgMap(extraArgMap);\n const combinedSpec = { ...rawArgMap, ...extraArgSpec };\n\n // Assert any missing arguments\n assertUnknownArgs(combinedSpec, args);\n\n // Collapse aliases into fully qualified arguments.\n args = collapseAliases(combinedSpec, args);\n\n // Filter out array-type arguments so _resolveStringOrBooleanArgs can process the rest.\n // This is necessary because _resolveStringOrBooleanArgs can't handle array-type args like --platform.\n const filteredArgs = filterOutArrayArgs(args, combinedSpec);\n\n // Resolve all of the string or boolean arguments and the project root.\n return _resolveStringOrBooleanArgs(combinedSpec, filteredArgs, allowedValues);\n}\n\n/**\n * Enables the resolution of boolean arguments that can be formatted like `--foo=true` or `--foo false`\n *\n * @param argv arguments that were passed to the command.\n * @param rawArgMap base argument spec defining valid arguments and their types.\n * @param extraArgMap extra arguments and aliases that should be resolved as string or boolean.\n * @returns parsed arguments and project root.\n */\nexport async function resolveCustomBooleanArgsAsync(\n argv: string[],\n rawArgMap: arg.Spec,\n extraArgMap: ExtraArgsSpec\n) {\n const results = await resolveStringOrBooleanArgsAsync(argv, rawArgMap, extraArgMap);\n\n return {\n ...results,\n args: Object.fromEntries(\n Object.entries(results.args).map(([key, value]) => {\n // Skip aliases (e.g. '-f': '--flag') - only process actual flags\n const extraArgValue = extraArgMap[key];\n if (extraArgValue && typeof extraArgValue !== 'string') {\n if (typeof value === 'string') {\n if (!['true', 'false'].includes(value)) {\n throw new CommandError(\n 'BAD_ARGS',\n `Invalid boolean argument: ${key}=${value}. Expected one of: true, false`\n );\n }\n return [key, value === 'true'];\n }\n }\n return [key, value];\n })\n ),\n };\n}\n\nexport function _resolveStringOrBooleanArgs(\n arg: Spec,\n args: string[],\n allowedValues?: Record<string, string[]>\n) {\n // Default project root, if a custom one is defined then it will overwrite this.\n let projectRoot: string = '.';\n // The resolved arguments.\n const settings: Record<string, string | boolean | undefined> = {};\n\n // Create a list of possible arguments, this will filter out aliases.\n const possibleArgs = Object.entries(arg)\n .filter(([, value]) => typeof value !== 'string')\n .map(([key]) => key);\n\n // Check if a value is allowed for a given flag\n const isAllowedValue = (flag: string, value: string): boolean => {\n if (!allowedValues || !allowedValues[flag]) {\n return true; // No restrictions, allow any value\n }\n return allowedValues[flag].includes(value);\n };\n\n // Loop over arguments in reverse order so we can resolve if a value belongs to a flag.\n for (let i = args.length - 1; i > -1; i--) {\n const value = args[i];\n // At this point we should have converted all aliases to fully qualified arguments.\n if (value.startsWith('--')) {\n // If we ever find an argument then it must be a boolean because we are checking in reverse\n // and removing arguments from the array if we find a string.\n // We don't override arguments that are already set\n if (!(value in settings)) {\n settings[value] = true;\n }\n } else {\n // Get the previous argument in the array.\n const nextValue = i > 0 ? args[i - 1] : null;\n if (nextValue && possibleArgs.includes(nextValue) && isAllowedValue(nextValue, value)) {\n // We don't override arguments that are already set\n if (!(nextValue in settings)) {\n settings[nextValue] = value;\n }\n i--;\n } else if (\n // If the last value is not a flag and it doesn't have a recognized flag before it (instead having a string value or nothing)\n // then it must be the project root.\n i ===\n args.length - 1\n ) {\n projectRoot = value;\n } else {\n // This will asserts if two strings are passed in a row and not at the end of the line.\n throw new CommandError('BAD_ARGS', `Unknown argument: ${value}`);\n }\n }\n }\n\n return {\n args: settings,\n projectRoot,\n };\n}\n\n/** Convert all aliases to fully qualified flag names. */\nexport function collapseAliases(arg: Spec, args: string[]): string[] {\n const aliasMap = getAliasTuples(arg);\n\n for (const [arg, alias] of aliasMap) {\n args = replaceAllValues(args, arg, alias);\n }\n\n // Assert if there are duplicate flags after we collapse the aliases.\n // Skip array-type arguments (like --platform) which can have multiple values.\n assertDuplicateArgs(args, aliasMap, arg);\n return args;\n}\n\n/** Assert that the spec has unknown arguments. */\nexport function assertUnknownArgs(arg: Spec, args: string[]) {\n const allowedArgs = Object.keys(arg);\n const unknownArgs = args.filter((arg) => !allowedArgs.includes(arg) && arg.startsWith('-'));\n if (unknownArgs.length > 0) {\n throw new CommandError(`Unknown arguments: ${unknownArgs.join(', ')}`);\n }\n}\n\nfunction getAliasTuples(arg: Spec): [string, string][] {\n return Object.entries(arg).filter(([, value]) => typeof value === 'string') as [string, string][];\n}\n\n/** Filter out array-type arguments from the spec (and their values).\n * This is needed because _resolveStringOrBooleanArgs can't handle array args like --platform.\n */\nfunction filterOutArrayArgs(args: string[], spec: Spec): string[] {\n // Get the set of flag names that are array types\n const arrayFlags = new Set(\n Object.entries(spec)\n .filter(([, value]) => Array.isArray(value))\n .map(([key]) => key)\n );\n\n if (arrayFlags.size === 0) {\n return args;\n }\n\n const result: string[] = [];\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arrayFlags.has(arg)) {\n // Skip this flag and its value if it has one\n if (i + 1 < args.length && !args[i + 1].startsWith('-')) {\n i++;\n }\n } else {\n result.push(arg);\n }\n }\n return result;\n}\n\n/** Asserts that a duplicate flag has been used, this naively throws without knowing if an alias or flag were used as the duplicate. */\nexport function assertDuplicateArgs(\n args: string[],\n argNameAliasTuple: [string, string][],\n spec?: Spec\n) {\n for (const [argName, argNameAlias] of argNameAliasTuple) {\n // Skip array-type arguments (like --platform) which can have multiple values\n if (spec && Array.isArray(spec[argNameAlias])) {\n continue;\n }\n if (args.filter((a) => [argName, argNameAlias].includes(a)).length > 1) {\n throw new CommandError(\n 'BAD_ARGS',\n `Can only provide one instance of ${argName} or ${argNameAlias}`\n );\n }\n }\n}\n\nexport function assertNonBooleanArg(argName: string, arg: any): asserts arg is string | string[] {\n if (arg == null || typeof arg === 'boolean') {\n throw new CommandError('BAD_ARGS', `Expected input for arg ${argName}`);\n }\n}\n"],"names":["_resolveStringOrBooleanArgs","assertDuplicateArgs","assertNonBooleanArg","assertUnknownArgs","collapseAliases","resolveCustomBooleanArgsAsync","resolveStringOrBooleanArgsAsync","parseExtraArgMap","extraArgMap","spec","allowedValues","key","value","Object","entries","Array","isArray","first","stringValues","Boolean","CommandError","splitArgs","args","result","arg","startsWith","props","split","push","length","join","argv","rawArgMap","extraArgSpec","combinedSpec","filteredArgs","filterOutArrayArgs","results","fromEntries","map","extraArgValue","includes","projectRoot","settings","possibleArgs","filter","isAllowedValue","flag","i","nextValue","aliasMap","getAliasTuples","alias","replaceAllValues","allowedArgs","keys","unknownArgs","arrayFlags","Set","size","has","argNameAliasTuple","argName","argNameAlias","a"],"mappings":";;;;;;;;;;;IAyIgBA,2BAA2B;eAA3BA;;IAyHAC,mBAAmB;eAAnBA;;IAmBAC,mBAAmB;eAAnBA;;IA9DAC,iBAAiB;eAAjBA;;IAdAC,eAAe;eAAfA;;IA9FMC,6BAA6B;eAA7BA;;IAhCAC,+BAA+B;eAA/BA;;;uBAzEW;wBACJ;AAU7B,iFAAiF,GACjF,SAASC,iBAAiBC,WAA0B;IAIlD,MAAMC,OAAiB,CAAC;IACxB,MAAMC,gBAA0C,CAAC;IAEjD,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAACN,aAAc;QACtD,IAAI,OAAOI,UAAU,UAAU;YAC7B,8BAA8B;YAC9BH,IAAI,CAACE,IAAI,GAAGC;QACd,OAAO,IAAIG,MAAMC,OAAO,CAACJ,QAAQ;YAC/B,0FAA0F;YAC1F,MAAM,CAACK,OAAO,GAAGC,aAAa,GAAGN;YACjC,IAAIK,UAAUE,SAAS;gBACrB,MAAM,IAAIC,oBAAY,CACpB,YACA,CAAC,6BAA6B,EAAET,IAAI,+BAA+B,CAAC;YAExE;YACAF,IAAI,CAACE,IAAI,GAAGQ;YACZT,aAAa,CAACC,IAAI,GAAG;gBAAC;gBAAQ;mBAAYO;aAAa;QACzD,OAAO;YACL,8BAA8B;YAC9BT,IAAI,CAACE,IAAI,GAAGQ;QACd;IACF;IAEA,OAAO;QAAEV;QAAMC;IAAc;AAC/B;AAEA,+FAA+F,GAC/F,SAASW,UAAUC,IAAc;IAC/B,MAAMC,SAAmB,EAAE;IAE3B,KAAK,MAAMC,OAAOF,KAAM;QACtB,IAAIE,IAAIC,UAAU,CAAC,MAAM;YACvB,MAAM,CAACd,KAAK,GAAGe,MAAM,GAAGF,IAAIG,KAAK,CA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,OAAOrC;IACT;IAEA,MAAMC,SAAmB,EAAE;IAC3B,IAAK,IAAIyB,IAAI,GAAGA,IAAI1B,KAAKO,MAAM,EAAEmB,IAAK;QACpC,MAAMxB,MAAMF,IAAI,CAAC0B,EAAE;QACnB,IAAIS,WAAWG,GAAG,CAACpC,MAAM;YACvB,6CAA6C;YAC7C,IAAIwB,IAAI,IAAI1B,KAAKO,MAAM,IAAI,CAACP,IAAI,CAAC0B,IAAI,EAAE,CAACvB,UAAU,CAAC,MAAM;gBACvDuB;YACF;QACF,OAAO;YACLzB,OAAOK,IAAI,CAACJ;QACd;IACF;IACA,OAAOD;AACT;AAGO,SAAStB,oBACdqB,IAAc,EACduC,iBAAqC,EACrCpD,IAAW;IAEX,KAAK,MAAM,CAACqD,SAASC,aAAa,IAAIF,kBAAmB;QACvD,6EAA6E;QAC7E,IAAIpD,QAAQM,MAAMC,OAAO,CAACP,IAAI,CAACsD,aAAa,GAAG;YAC7C;QACF;QACA,IAAIzC,KAAKuB,MAAM,CAAC,CAACmB,IAAM;gBAACF;gBAASC;aAAa,CAACtB,QAAQ,CAACuB,IAAInC,MAAM,GAAG,GAAG;YACtE,MAAM,IAAIT,oBAAY,CACpB,YACA,CAAC,iCAAiC,EAAE0C,QAAQ,IAAI,EAAEC,cAAc;QAEpE;IACF;AACF;AAEO,SAAS7D,oBAAoB4D,OAAe,EAAEtC,GAAQ;IAC3D,IAAIA,OAAO,QAAQ,OAAOA,QAAQ,WAAW;QAC3C,MAAM,IAAIJ,oBAAY,CAAC,YAAY,CAAC,uBAAuB,EAAE0C,SAAS;IACxE;AACF"}
|
|
@@ -33,7 +33,7 @@ class FetchClient {
|
|
|
33
33
|
this.headers = {
|
|
34
34
|
accept: 'application/json',
|
|
35
35
|
'content-type': 'application/json',
|
|
36
|
-
'user-agent': `expo-cli/${"55.0.
|
|
36
|
+
'user-agent': `expo-cli/${"55.0.3"}`,
|
|
37
37
|
authorization: 'Basic ' + _nodebuffer().Buffer.from(`${target}:`).toString('base64')
|
|
38
38
|
};
|
|
39
39
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@expo/cli",
|
|
3
|
-
"version": "55.0.
|
|
3
|
+
"version": "55.0.3",
|
|
4
4
|
"description": "The Expo CLI",
|
|
5
5
|
"main": "build/bin/cli",
|
|
6
6
|
"bin": {
|
|
@@ -43,21 +43,21 @@
|
|
|
43
43
|
"dependencies": {
|
|
44
44
|
"@0no-co/graphql.web": "^1.0.8",
|
|
45
45
|
"@expo/code-signing-certificates": "^0.0.6",
|
|
46
|
-
"@expo/config": "~55.0.
|
|
47
|
-
"@expo/config-plugins": "~55.0.
|
|
46
|
+
"@expo/config": "~55.0.3",
|
|
47
|
+
"@expo/config-plugins": "~55.0.3",
|
|
48
48
|
"@expo/devcert": "^1.2.1",
|
|
49
|
-
"@expo/env": "~2.0.
|
|
50
|
-
"@expo/image-utils": "^0.8.
|
|
51
|
-
"@expo/json-file": "^10.0.
|
|
49
|
+
"@expo/env": "~2.0.11",
|
|
50
|
+
"@expo/image-utils": "^0.8.11",
|
|
51
|
+
"@expo/json-file": "^10.0.11",
|
|
52
52
|
"@expo/metro": "~54.2.0",
|
|
53
|
-
"@expo/metro-config": "~55.0.
|
|
54
|
-
"@expo/osascript": "^2.4.
|
|
55
|
-
"@expo/package-manager": "^1.10.
|
|
56
|
-
"@expo/plist": "^0.5.
|
|
57
|
-
"@expo/prebuild-config": "^55.0.
|
|
58
|
-
"@expo/router-server": "^55.0.
|
|
59
|
-
"@expo/log-box": "55.0.
|
|
60
|
-
"@expo/schema-utils": "^55.0.
|
|
53
|
+
"@expo/metro-config": "~55.0.3",
|
|
54
|
+
"@expo/osascript": "^2.4.2",
|
|
55
|
+
"@expo/package-manager": "^1.10.2",
|
|
56
|
+
"@expo/plist": "^0.5.2",
|
|
57
|
+
"@expo/prebuild-config": "^55.0.3",
|
|
58
|
+
"@expo/router-server": "^55.0.2",
|
|
59
|
+
"@expo/log-box": "55.0.2",
|
|
60
|
+
"@expo/schema-utils": "^55.0.2",
|
|
61
61
|
"@expo/spawn-async": "^1.7.2",
|
|
62
62
|
"@expo/ws-tunnel": "^1.0.1",
|
|
63
63
|
"@expo/xcpretty": "^4.3.0",
|
|
@@ -76,8 +76,7 @@
|
|
|
76
76
|
"debug": "^4.3.4",
|
|
77
77
|
"dnssd-advertise": "^1.1.1",
|
|
78
78
|
"env-editor": "^0.4.1",
|
|
79
|
-
"expo-server": "^55.0.
|
|
80
|
-
"freeport-async": "^2.0.0",
|
|
79
|
+
"expo-server": "^55.0.2",
|
|
81
80
|
"getenv": "^2.0.0",
|
|
82
81
|
"glob": "^13.0.0",
|
|
83
82
|
"lan-network": "^0.1.6",
|
|
@@ -86,7 +85,6 @@
|
|
|
86
85
|
"npm-package-arg": "^11.0.0",
|
|
87
86
|
"ora": "^3.4.0",
|
|
88
87
|
"picomatch": "^3.0.1",
|
|
89
|
-
"pretty-bytes": "^5.6.0",
|
|
90
88
|
"pretty-format": "^29.7.0",
|
|
91
89
|
"progress": "^2.0.3",
|
|
92
90
|
"prompts": "^2.3.2",
|
|
@@ -159,7 +157,7 @@
|
|
|
159
157
|
"@types/ws": "^8.5.4",
|
|
160
158
|
"devtools-protocol": "^0.0.1113120",
|
|
161
159
|
"expo-atlas": "^0.4.1",
|
|
162
|
-
"expo-module-scripts": "^55.0.
|
|
160
|
+
"expo-module-scripts": "^55.0.2",
|
|
163
161
|
"find-process": "^1.4.7",
|
|
164
162
|
"jest-runner-tsd": "^6.0.0",
|
|
165
163
|
"klaw-sync": "^6.0.0",
|
|
@@ -172,5 +170,5 @@
|
|
|
172
170
|
"tree-kill": "^1.2.2",
|
|
173
171
|
"tsd": "^0.28.1"
|
|
174
172
|
},
|
|
175
|
-
"gitHead": "
|
|
173
|
+
"gitHead": "7d7f6762fc6907c27a329953c682134a84410dea"
|
|
176
174
|
}
|