|
| 1 | +const { writeFileSync, existsSync } = require("fs"); |
| 2 | +const { resolve } = require("path"); |
| 3 | +const { Buffer } = require("buffer"); |
| 4 | +const chalk = require("chalk"); |
| 5 | + |
| 6 | +const NAME = require("../package.json").name; |
| 7 | + |
| 8 | +function getDefaultSerializer() { |
| 9 | + const bundleToString = require("metro/src/lib/bundleToString"); |
| 10 | + const baseJSBundle = require("metro/src/DeltaBundler/Serializers/baseJSBundle"); |
| 11 | + |
| 12 | + return (entryPoint, preModules, graph, options) => |
| 13 | + bundleToString(baseJSBundle(entryPoint, preModules, graph, options)).code; |
| 14 | +} |
| 15 | + |
| 16 | +function getStringSizeInBytes(str) { |
| 17 | + return Buffer.byteLength(str, "utf8"); |
| 18 | +} |
| 19 | + |
| 20 | +/** |
| 21 | + * `/Users/i/app/node_modules/metro/node_modules/@babel/runtime/helpers/createClass.js` -> `@babel/runtime` |
| 22 | + * `/Users/i/app/node_modules/react/jsx-runtime.js` -> `react` |
| 23 | + */ |
| 24 | +function getPackageNameFromPath(path) { |
| 25 | + const parts = path.split("node_modules/"); |
| 26 | + const lastPart = parts[parts.length - 1]; |
| 27 | + if (lastPart.startsWith("@")) { |
| 28 | + return lastPart.split("/").slice(0, 2).join("/"); |
| 29 | + } |
| 30 | + return lastPart.split("/")[0]; |
| 31 | +} |
| 32 | + |
| 33 | +/** |
| 34 | + * `/Users/i/app/node_modules/metro/node_modules/@babel/runtime/helpers/createClass.js` -> `/Users/i/app/node_modules/metro/node_modules/@babel/runtime` |
| 35 | + * `/Users/i/app/node_modules/react/jsx-runtime.js` -> `/Users/i/app/node_modules/react` |
| 36 | + */ |
| 37 | +function getPackageAbsolutePath(path, pkgName) { |
| 38 | + const parts = path.split("node_modules/"); |
| 39 | + parts[parts.length - 1] = pkgName; |
| 40 | + return parts.join("node_modules/"); |
| 41 | +} |
| 42 | + |
| 43 | +function toPackages(modules) { |
| 44 | + const packages = new Map(); |
| 45 | + modules.forEach((module) => { |
| 46 | + if (!module.path.includes("node_modules/")) { |
| 47 | + return; |
| 48 | + } |
| 49 | + |
| 50 | + const pkgName = getPackageNameFromPath(module.path); |
| 51 | + const absolutePkgPath = getPackageAbsolutePath(module.path, pkgName); |
| 52 | + |
| 53 | + if (!packages.has(absolutePkgPath)) { |
| 54 | + packages.set(absolutePkgPath, { |
| 55 | + name: pkgName, |
| 56 | + absolutePath: absolutePkgPath, |
| 57 | + version: require(resolve(absolutePkgPath, "package.json")).version, |
| 58 | + }); |
| 59 | + } |
| 60 | + }); |
| 61 | + |
| 62 | + return Array.from(packages.values()).sort((a, b) => |
| 63 | + a.name.localeCompare(b.name), |
| 64 | + ); |
| 65 | +} |
| 66 | + |
| 67 | +function toModuleStruct(m, includeCode) { |
| 68 | + const sourceCode = m.getSource().toString("utf8"); |
| 69 | + const outputCode = m.output[0].data.code; |
| 70 | + return { |
| 71 | + path: m.path, |
| 72 | + source: { |
| 73 | + code: includeCode ? sourceCode : "", |
| 74 | + lineCount: sourceCode.split("\n").length, |
| 75 | + sizeInBytes: getStringSizeInBytes(sourceCode), |
| 76 | + }, |
| 77 | + output: { |
| 78 | + code: includeCode ? outputCode : "", |
| 79 | + lineCount: m.output[0].data.lineCount, |
| 80 | + sizeInBytes: getStringSizeInBytes(outputCode), |
| 81 | + }, |
| 82 | + dependencies: Array.from(m?.dependencies?.values?.() ?? []).map((e) => ({ |
| 83 | + absolutePath: e.absolutePath, |
| 84 | + name: e.data.name, |
| 85 | + })), |
| 86 | + }; |
| 87 | +} |
| 88 | + |
| 89 | +function createJsonReport({ |
| 90 | + graph, |
| 91 | + entryPoint, |
| 92 | + includeEnvs, |
| 93 | + preModules, |
| 94 | + includeCode, |
| 95 | + outputJsonPath, |
| 96 | + rootFolder, |
| 97 | +}) { |
| 98 | + const dependencies = Array.from(graph.dependencies.values()); |
| 99 | + |
| 100 | + const stats = { |
| 101 | + date: Date.now(), |
| 102 | + entryPoint, |
| 103 | + transformOptions: graph.transformOptions, |
| 104 | + envs: includeEnvs.reduce((acc, envName) => { |
| 105 | + acc[envName] = process.env[envName]; |
| 106 | + return acc; |
| 107 | + }, {}), |
| 108 | + rootFolder, |
| 109 | + packages: toPackages(dependencies), |
| 110 | + modules: preModules |
| 111 | + .map((m) => toModuleStruct(m, includeCode)) |
| 112 | + .concat(dependencies.map((m) => toModuleStruct(m, includeCode))), |
| 113 | + }; |
| 114 | + |
| 115 | + writeFileSync(outputJsonPath, JSON.stringify(stats)); |
| 116 | + |
| 117 | + console.log( |
| 118 | + `${chalk.yellow(`[${NAME}]`)}: Saved stats to ${chalk.green(outputJsonPath)}`, |
| 119 | + ); |
| 120 | +} |
| 121 | + |
| 122 | +/** |
| 123 | + * Creates a custom serializer function for Metro bundler, which generates a JSON report |
| 124 | + * and optionally modifies the serialization process. |
| 125 | + * |
| 126 | + * @param {Object} options - Configuration options for the serializer. |
| 127 | + * @param {Function} [options.serializer] - A custom serializer function. If not provided, a default serializer is used. |
| 128 | + * @param {string} options.projectRoot - The root directory of the project. Must exist. |
| 129 | + * @param {string} [options.outputJsonPath] - The path where the JSON report will be saved. Defaults to "metro-stats.json" in the project root. |
| 130 | + * @param {boolean} [options.includeCode=true] - Whether to include the source and output code in the JSON report. |
| 131 | + * @param {string[]} [options.includeEnvs=[]] - A list of environment variable names to include in the JSON report. |
| 132 | + * @returns {Function} - A custom serializer function to be used by Metro. |
| 133 | + * @throws {Error} - Throws an error if the project root does not exist. |
| 134 | + */ |
| 135 | +function createSerializer({ |
| 136 | + serializer, |
| 137 | + projectRoot, |
| 138 | + outputJsonPath, |
| 139 | + includeCode = true, |
| 140 | + includeEnvs = [], |
| 141 | +} = {}) { |
| 142 | + const mySerializer = serializer || getDefaultSerializer(); |
| 143 | + |
| 144 | + if (!existsSync(projectRoot)) { |
| 145 | + throw new Error(`[${NAME}]: Project root does not exist: ${projectRoot}`); |
| 146 | + } |
| 147 | + |
| 148 | + const myOutputJsonPath = |
| 149 | + outputJsonPath ?? resolve(projectRoot, "metro-stats.json"); |
| 150 | + |
| 151 | + function customSerializer(entryPoint, preModules, graph, options) { |
| 152 | + const code = mySerializer(entryPoint, preModules, graph, options); |
| 153 | + |
| 154 | + createJsonReport({ |
| 155 | + graph, |
| 156 | + entryPoint, |
| 157 | + includeEnvs, |
| 158 | + preModules, |
| 159 | + includeCode, |
| 160 | + outputJsonPath: myOutputJsonPath, |
| 161 | + rootFolder: projectRoot, |
| 162 | + }); |
| 163 | + |
| 164 | + return code; |
| 165 | + } |
| 166 | + |
| 167 | + return customSerializer; |
| 168 | +} |
| 169 | + |
| 170 | +module.exports = { createSerializer }; |
0 commit comments