react-native-bundle-discovery 1.3.1 → 2.0.0-rc.2

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.
@@ -1,196 +0,0 @@
1
- const { parse } = require("path");
2
- const { writeFileSync, existsSync } = require("fs");
3
- const { resolve } = require("path");
4
- const { Buffer } = require("buffer");
5
- const chalk = require("chalk");
6
-
7
- const NAME = require("../package.json").name;
8
-
9
- function getDefault(module) {
10
- return module.__esModule ? module.default : module;
11
- }
12
-
13
- function getDefaultSerializer() {
14
- const metroPath = parse(require.resolve("metro/package.json")).dir;
15
- const bundleToString = getDefault(
16
- require(`${metroPath}/src/lib/bundleToString.js`),
17
- );
18
- const baseJSBundle = getDefault(
19
- require(`${metroPath}/src/DeltaBundler/Serializers/baseJSBundle.js`),
20
- );
21
-
22
- return function defaultSerializer(entryPoint, preModules, graph, options) {
23
- let bundle = baseJSBundle(entryPoint, preModules, graph, options);
24
-
25
- // Sentry support
26
- // https://docs.sentry.io/platforms/react-native/manual-setup/metro/#wrap-your-custom-serializer
27
- if (typeof options?.sentryBundleCallback === "function") {
28
- bundle = options.sentryBundleCallback(bundle);
29
- }
30
-
31
- return bundleToString(bundle).code;
32
- };
33
- }
34
-
35
- function getStringSizeInBytes(str) {
36
- return Buffer.byteLength(str, "utf8");
37
- }
38
-
39
- /**
40
- * `/Users/i/app/node_modules/metro/node_modules/@babel/runtime/helpers/createClass.js` -> `@babel/runtime`
41
- * `/Users/i/app/node_modules/react/jsx-runtime.js` -> `react`
42
- */
43
- function getPackageNameFromPath(path) {
44
- const parts = path.split("node_modules/");
45
- const lastPart = parts[parts.length - 1];
46
- if (lastPart.startsWith("@")) {
47
- return lastPart.split("/").slice(0, 2).join("/");
48
- }
49
- return lastPart.split("/")[0];
50
- }
51
-
52
- /**
53
- * `/Users/i/app/node_modules/metro/node_modules/@babel/runtime/helpers/createClass.js` -> `/Users/i/app/node_modules/metro/node_modules/@babel/runtime`
54
- * `/Users/i/app/node_modules/react/jsx-runtime.js` -> `/Users/i/app/node_modules/react`
55
- */
56
- function getPackageAbsolutePath(path, pkgName) {
57
- const parts = path.split("node_modules/");
58
- parts[parts.length - 1] = pkgName;
59
- return parts.join("node_modules/");
60
- }
61
-
62
- function toPackages(modules) {
63
- const packages = new Map();
64
- modules.forEach((module) => {
65
- if (!module.path.includes("node_modules/")) {
66
- return;
67
- }
68
-
69
- const pkgName = getPackageNameFromPath(module.path);
70
- const absolutePkgPath = getPackageAbsolutePath(module.path, pkgName);
71
-
72
- if (!packages.has(absolutePkgPath)) {
73
- packages.set(absolutePkgPath, {
74
- name: pkgName,
75
- absolutePath: absolutePkgPath,
76
- version: require(resolve(absolutePkgPath, "package.json")).version,
77
- });
78
- }
79
- });
80
-
81
- return Array.from(packages.values()).sort((a, b) =>
82
- a.name.localeCompare(b.name),
83
- );
84
- }
85
-
86
- function toModuleStruct(m, includeCode) {
87
- const sourceCode = m.getSource().toString("utf8");
88
- const outputCode = m.output[0].data.code;
89
- return {
90
- path: m.path,
91
- source: {
92
- code: includeCode ? sourceCode : "",
93
- lineCount: sourceCode.split("\n").length,
94
- sizeInBytes: getStringSizeInBytes(sourceCode),
95
- },
96
- output: {
97
- code: includeCode ? outputCode : "",
98
- lineCount: m.output[0].data.lineCount,
99
- sizeInBytes: getStringSizeInBytes(outputCode),
100
- },
101
- dependencies: Array.from(m?.dependencies?.values?.() ?? [])
102
- .filter((e) => e.absolutePath)
103
- .map((e) => ({
104
- absolutePath: e.absolutePath,
105
- name: e.data.name,
106
- })),
107
- };
108
- }
109
-
110
- function createJsonReport({
111
- graph,
112
- entryPoint,
113
- includeEnvs,
114
- preModules,
115
- includeCode,
116
- outputJsonPath,
117
- rootFolder,
118
- silent,
119
- }) {
120
- const dependencies = Array.from(graph.dependencies.values());
121
-
122
- const stats = {
123
- date: Date.now(),
124
- entryPoint,
125
- transformOptions: graph.transformOptions,
126
- envs: includeEnvs.reduce((acc, envName) => {
127
- acc[envName] = process.env[envName];
128
- return acc;
129
- }, {}),
130
- rootFolder,
131
- packages: toPackages(preModules).concat(toPackages(dependencies)),
132
- modules: preModules
133
- .map((m) => toModuleStruct(m, includeCode))
134
- .concat(dependencies.map((m) => toModuleStruct(m, includeCode))),
135
- };
136
-
137
- writeFileSync(outputJsonPath, JSON.stringify(stats));
138
-
139
- if (!silent) {
140
- console.log(
141
- `${chalk.yellow(`[${NAME}]`)}: Saved stats to ${chalk.green(outputJsonPath)}`,
142
- );
143
- }
144
- }
145
-
146
- /**
147
- * Creates a custom serializer function for Metro bundler, which generates a JSON report
148
- * and optionally modifies the serialization process.
149
- *
150
- * @param {Object} options - Configuration options for the serializer.
151
- * @param {Function} [options.serializer] - A custom serializer function. If not provided, a default serializer is used.
152
- * @param {string} options.projectRoot - The root directory of the project. Must exist.
153
- * @param {string} [options.outputJsonPath] - The path where the JSON report will be saved. Defaults to "metro-stats.json" in the project root.
154
- * @param {boolean} [options.includeCode=true] - Whether to include the source and output code in the JSON report.
155
- * @param {string[]} [options.includeEnvs=[]] - A list of environment variable names to include in the JSON report.
156
- * @returns {Function} - A custom serializer function to be used by Metro.
157
- * @throws {Error} - Throws an error if the project root does not exist.
158
- */
159
- function createSerializer({
160
- serializer,
161
- projectRoot,
162
- outputJsonPath,
163
- includeCode = true,
164
- silent = false,
165
- includeEnvs = [],
166
- } = {}) {
167
- const mySerializer = serializer || getDefaultSerializer();
168
-
169
- if (!existsSync(projectRoot)) {
170
- throw new Error(`[${NAME}]: Project root does not exist: ${projectRoot}`);
171
- }
172
-
173
- const myOutputJsonPath =
174
- outputJsonPath ?? resolve(projectRoot, "metro-stats.json");
175
-
176
- function customSerializer(entryPoint, preModules, graph, options) {
177
- const code = mySerializer(entryPoint, preModules, graph, options);
178
-
179
- createJsonReport({
180
- graph,
181
- entryPoint,
182
- includeEnvs,
183
- preModules,
184
- includeCode,
185
- outputJsonPath: myOutputJsonPath,
186
- rootFolder: projectRoot,
187
- silent,
188
- });
189
-
190
- return code;
191
- }
192
-
193
- return customSerializer;
194
- }
195
-
196
- module.exports = { createSerializer };
package/lib/server.js DELETED
@@ -1,82 +0,0 @@
1
- const fs = require("fs");
2
- const path = require("path");
3
- const chalk = require("chalk");
4
- const { createServer } = require("@discoveryjs/cli");
5
- const { silent } = require("@discoveryjs/cli/lib/shared/utils.js");
6
- const config = require("../.discoveryrc.js");
7
-
8
- function serve(filePath, port, verbose) {
9
- const PORT = process.env.PORT || port;
10
-
11
- if (verbose) {
12
- console.info(
13
- `start server with file: ${filePath} on port: ${port} ${process.env.PORT ? `(${chalk.yellow("PORT")} env)` : ""}`,
14
- );
15
- }
16
-
17
- if (!filePath) {
18
- console.error(
19
- `Usage: '${chalk.green("npx react-native-bundle-discovery server <path-to-file>")}', Please provide a path to a JSON file.`,
20
- );
21
- process.exit(1);
22
- }
23
-
24
- const jsonFilePath = path.resolve(process.cwd(), filePath);
25
- if (verbose) {
26
- console.info(
27
- `Loading JSON file from: ${chalk.green(jsonFilePath)}, base directory: ${chalk.green(process.cwd())}`,
28
- );
29
- }
30
-
31
- let fullJsonPath;
32
-
33
- try {
34
- fullJsonPath = require.resolve(jsonFilePath);
35
- } catch (err) {
36
- console.error(`❌Error loading file: ${chalk.red(jsonFilePath)}\n\n`);
37
- console.error(err.message);
38
- process.exit(1);
39
- }
40
-
41
- const configFile = path.resolve(__dirname, "./.tmp.js");
42
-
43
- if (verbose) {
44
- console.info(
45
- `Creating temporary config file at: ${chalk.green(configFile)}, for discovery.js`,
46
- );
47
- }
48
- fs.writeFileSync(
49
- configFile,
50
- `module.exports = ${JSON.stringify(
51
- { ...config, data: "<tmp>" },
52
- null,
53
- 1,
54
- ).replace(`"<tmp>"`, `() => require("${fullJsonPath}")`)};`,
55
- );
56
-
57
- if (verbose) {
58
- console.info(`Running server with config: ${chalk.green(configFile)}`);
59
- }
60
-
61
- return silent(() =>
62
- createServer({
63
- cache: false,
64
- minify: true,
65
- dev: false,
66
- config: configFile,
67
- configFile,
68
- }).then((server) =>
69
- server.listen(PORT, () => {
70
- console.log(
71
- `[react-native-bundle-discovery]: 🚀 Server listen on ${chalk.green.underline(
72
- chalk.green(`http://localhost:${PORT}`),
73
- )}`,
74
- );
75
- }),
76
- ),
77
- );
78
- }
79
-
80
- module.exports = {
81
- serve,
82
- };
package/pages/_common.js DELETED
@@ -1,267 +0,0 @@
1
- const platformColor = `transformOptions.platform = 'android' ? 'rgba(194, 239, 116, .4)' : 'rgba(119, 31, 218, .4)'`;
2
-
3
- function getPackage(entry) {
4
- return `
5
- $packages: $.packages;
6
- $totalSize: $.modules.sum(=>output.sizeInBytes);
7
- $toModule: => {
8
- ext: $.path.getFileExtension(),
9
- name: $.path,
10
- size: $.output.sizeInBytes.formatBytes(),
11
- percent: ($.output.sizeInBytes / $totalSize).percent(3),
12
- };
13
-
14
- ${entry}.group(=> path.getModulesName())
15
- .map(=> ({
16
- $pkgName: $.key;
17
- pkgName: $pkgName, // example: lodash
18
- size: $.value.sum(=>output.sizeInBytes),
19
- pkgInstances: $.value
20
- .group(=> path.split($pkgName).pick(0) + $pkgName)
21
- .map(=> {
22
- $pkgNameWithPath: $.key;
23
- pkgName: $pkgNameWithPath, // example: node_modules/lodash
24
- version: $packages.[path = $pkgNameWithPath][0].version,
25
- size: $.value.sum(=> output.sizeInBytes),
26
- modules: $.value.map(=> $.$toModule()),
27
- }),
28
- }))`;
29
- }
30
-
31
- function getPackageList({
32
- data,
33
- itemPkgName,
34
- showCopiesBadge,
35
- expanded,
36
- limit,
37
- subLimit,
38
- }) {
39
- return {
40
- view: "list",
41
- data,
42
- emptyText: "⚠️ No packages found",
43
- limit,
44
- item: {
45
- view: "tree",
46
- expanded,
47
- itemConfig: {
48
- content: [
49
- itemPkgName,
50
- "text: ' '",
51
- "pill-badge:{ text: size.formatBytes(), color: 'rgba(120, 177, 9, 0.35)' }",
52
- showCopiesBadge
53
- ? {
54
- view: "pill-badge",
55
- when: "pkgInstances.size() > 1",
56
- data: "(pkgInstances.size() - 1).pluralBadge(['copy','copies'], '+')",
57
- color: "rgba(255, 0, 0, 0.35)",
58
- }
59
- : null,
60
- {
61
- view: "pill-badge",
62
- data: "pkgInstances.modules.size().pluralBadge(['file','files'])",
63
- },
64
- ].filter(Boolean),
65
- children: `$.pkgInstances`,
66
- itemConfig: {
67
- view: "tree-leaf",
68
- limit: subLimit,
69
- content: [
70
- //
71
- "text:pkgName",
72
- "text:' '",
73
- "pill-badge:{ text: 'v' + version, color: '#0af' }",
74
- "pill-badge:{ text: size.formatBytes(), color: 'rgba(120, 177, 9, 0.35)' }",
75
- {
76
- view: "pill-badge",
77
- data: "modules.size().pluralBadge(['file','files'])",
78
- },
79
- ],
80
- children: `$.modules`,
81
- itemConfig: {
82
- view: "tree-leaf",
83
- content: getTreeModule({ hasPercent: true }),
84
- },
85
- },
86
- },
87
- },
88
- };
89
- }
90
-
91
- function getTreeModule({ hasTextMatch = false, hasPercent = false } = {}) {
92
- return [
93
- "pill-badge:{ text: ext, color: ext.getExtColor() }",
94
- hasTextMatch
95
- ? {
96
- view: "link",
97
- content: hasTextMatch ? "text-match" : "text",
98
- data: `{
99
- href: name.pageLink("module", {}),
100
- text: name,
101
- match: #.filterByPathStr
102
- }`,
103
- }
104
- : {
105
- view: "link",
106
- data: `{ href: $.name.pageLink("module", {}), text: $.name }`,
107
- },
108
- "text:' '",
109
- {
110
- view: "badge",
111
- when: "isEntry",
112
- text: "Entrypoint",
113
- color: "gold",
114
- textColor: "black",
115
- },
116
- "pill-badge:{ text: size, color: 'rgba(120, 177, 9, 0.35)' }",
117
- hasPercent
118
- ? "pill-badge:{ text: percent, color: 'rgba(120, 177, 9, 0.35)' }"
119
- : null,
120
- ].filter(Boolean);
121
- }
122
- function getModulesTree({ data, limit }) {
123
- if (!data) {
124
- throw new Error("[getModulesTree]: data is required");
125
- }
126
- return {
127
- view: "content-filter",
128
- data,
129
- name: "filterByPathStr",
130
- content: {
131
- view: "list",
132
- limit,
133
- data: ".[name ~= #.filterByPathStr]",
134
- emptyText: "⚠️ No modules found",
135
- item: {
136
- view: "tree",
137
- expanded: false,
138
- itemConfig: {
139
- content: getTreeModule({ hasTextMatch: true }),
140
- children: `
141
- [
142
- {
143
- title:'Imported by modules',
144
- data: $.reasons,
145
- type: 'reasons',
146
- },
147
- {
148
- title:'Similar copies',
149
- data: $.duplicates,
150
- type: 'duplicates',
151
- }
152
- ].filter(=> $.data.size() > 0)
153
- `,
154
- itemConfig: {
155
- view: "switch",
156
- content: [
157
- {
158
- when: 'type="reasons"',
159
- content: {
160
- view: "tree-leaf",
161
- content: [
162
- "text:title",
163
- "text:' '",
164
- "badge:{ text: $.data.size() }",
165
- ],
166
- children: `$.data`,
167
- itemConfig: {
168
- view: "tree-leaf",
169
- content: getTreeModule(),
170
- },
171
- },
172
- },
173
- {
174
- when: 'type="duplicates"',
175
- content: {
176
- view: "tree-leaf",
177
- content: [
178
- "text:title",
179
- "text:' '",
180
- "badge:{ text: $.data.size() }",
181
- ],
182
- children: `$.data`,
183
- itemConfig: {
184
- view: "tree-leaf",
185
- content: getTreeModule(),
186
- },
187
- },
188
- },
189
- ],
190
- },
191
- },
192
- },
193
- },
194
- };
195
- }
196
-
197
- const metadata = {
198
- platform: {
199
- when: "transformOptions.platform",
200
- view: "badge",
201
- data: `{ prefix: 'Platform: ', text: transformOptions.platform, color: ${platformColor} }`,
202
- },
203
- size: {
204
- when: "modules.filter(=> $.path has 'node_modules').size()",
205
- view: "badge",
206
- data: `{ prefix: 'Size: ', text: modules.sum(=>output.sizeInBytes).formatBytes(), color: ${platformColor} }`,
207
- },
208
- node_modules_size: {
209
- when: "modules.filter(=> $.path has 'node_modules').size()",
210
- view: "badge",
211
- data: "{ prefix: 'node_modules: ', text: modules.filter(=> $.path has 'node_modules').sum(=>output.sizeInBytes).formatBytes(), color: 'rgba(255, 0, 0, 0.35)' }",
212
- },
213
- source_code_size: {
214
- when: "modules.filter(=> $.path has 'node_modules').size()",
215
- view: "badge",
216
- data: `
217
- // vars
218
- $totalSize: modules.sum(=>output.sizeInBytes);
219
- $thirdPartySize: modules.filter(=> $.path has 'node_modules').sum(=>output.sizeInBytes);
220
- // return data
221
- { prefix: 'Source code: ', text: ($totalSize - $thirdPartySize).formatBytes(), color: 'rgba(148, 111, 234, 0.5)' }`,
222
- },
223
- is_dev: {
224
- when: "transformOptions.dev != null",
225
- view: "badge",
226
- data: "{ prefix: '__DEV__: ', text: transformOptions.dev }",
227
- },
228
- is_minified: {
229
- when: "transformOptions.minify != null",
230
- view: "badge",
231
- data: "{ prefix: 'Minify: ', text: transformOptions.minify }",
232
- },
233
- };
234
-
235
- const externalLinkHtml = `<svg class="my-icon my-icon-link" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" ><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6M15 3h6v6M10 14 21 3"></path></svg>`;
236
-
237
- function getCopyToClipboardButton({ textToCopy, className, text }) {
238
- return {
239
- view: "button",
240
- className: `${className ?? ""} copy-to-clipboard`,
241
- text,
242
- data: `{ textToCopy: ${textToCopy} }`,
243
- onClick(elm, data) {
244
- clearTimeout(elm.__timer);
245
- navigator.clipboard
246
- .writeText(data.textToCopy)
247
- .then(() => {
248
- elm.classList.add("done");
249
- elm.__timer = setTimeout(() => elm.classList.remove("done"), 2000);
250
- })
251
- .catch(() => {
252
- elm.classList.add("err");
253
- elm.__timer = setTimeout(() => elm.classList.remove("err"), 2000);
254
- });
255
- },
256
- };
257
- }
258
-
259
- module.exports = {
260
- getCopyToClipboardButton,
261
- getPackage,
262
- getPackageList,
263
- externalLinkHtml,
264
- getTreeModule,
265
- getModulesTree,
266
- metadata,
267
- };