@gfean/react-native-bundle-drop 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/BundleDrop.podspec +17 -20
  2. package/README.md +60 -1
  3. package/android/build.gradle +4 -0
  4. package/android/src/main/java/com/bundledrop/BundleDropFileOps.kt +20 -0
  5. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +4 -1
  6. package/android/src/main/java/com/bundledrop/BundleDropNativePaths.kt +5 -1
  7. package/docs/native-fingerprint.md +211 -0
  8. package/expo/android/build.gradle +61 -56
  9. package/ios/BundleDropLocator.swift +12 -0
  10. package/ios/BundleDropModule.swift +31 -13
  11. package/ios/BundleDropReactContent.swift +54 -0
  12. package/ios/BundleDropStartupRecovery.swift +48 -2
  13. package/ios/BundleDropStartupRecoveryAdapter.swift +87 -30
  14. package/lib/CLI/cli.js +9 -0
  15. package/lib/CLI/scripts/doctor.js +18 -7
  16. package/lib/CLI/scripts/expo/configure-expo.js +8 -3
  17. package/lib/CLI/scripts/fingerprint-cli.d.ts +12 -0
  18. package/lib/CLI/scripts/fingerprint-cli.js +36 -0
  19. package/lib/CLI/scripts/native/write-runtime-identity.js +3 -1
  20. package/lib/CLI/scripts/sight-ota.js +12 -3
  21. package/lib/CLI/scripts/upload-cli.d.ts +1 -0
  22. package/lib/CLI/scripts/upload-cli.js +43 -0
  23. package/lib/context.js +9 -1
  24. package/lib/errors.d.ts +2 -1
  25. package/lib/errors.js +2 -1
  26. package/lib/expo/buildIdentity.d.ts +1 -1
  27. package/lib/expo/buildIdentity.js +3 -0
  28. package/lib/expo/runtimeVersion.d.ts +10 -0
  29. package/lib/expo/runtimeVersion.js +11 -9
  30. package/lib/fingerprint/client.d.ts +5 -0
  31. package/lib/fingerprint/client.js +21 -0
  32. package/lib/fingerprint/collect.d.ts +3 -0
  33. package/lib/fingerprint/collect.js +116 -0
  34. package/lib/fingerprint/config.d.ts +14 -0
  35. package/lib/fingerprint/config.js +60 -0
  36. package/lib/fingerprint/normalizeBuildNumber.d.ts +4 -0
  37. package/lib/fingerprint/normalizeBuildNumber.js +55 -0
  38. package/lib/fingerprint/normalizeIosBuildNumber.d.ts +4 -0
  39. package/lib/fingerprint/normalizeIosBuildNumber.js +62 -0
  40. package/lib/fingerprint/types.d.ts +29 -0
  41. package/lib/fingerprint/types.js +2 -0
  42. package/lib/fingerprint/worker.d.ts +1 -0
  43. package/lib/fingerprint/worker.js +24 -0
  44. package/lib/fs/installedReportHistory.d.ts +2 -0
  45. package/lib/fs/installedReportHistory.js +55 -0
  46. package/lib/loadConfig.d.ts +6 -2
  47. package/lib/manager/downloadAndInstall.d.ts +1 -0
  48. package/lib/manager/downloadAndInstall.js +4 -0
  49. package/lib/manager/pendingRollback.d.ts +11 -0
  50. package/lib/manager/pendingRollback.js +54 -0
  51. package/lib/manager/reporting.d.ts +1 -0
  52. package/lib/manager/reporting.js +23 -6
  53. package/lib/manager/updateState.d.ts +3 -0
  54. package/lib/manager/updateState.js +1 -0
  55. package/lib/metro.js +3 -0
  56. package/lib/native/bundleDropNative.d.ts +2 -0
  57. package/lib/native/bundleDropNative.js +15 -5
  58. package/lib/patch-engine/installFromPatchSet.js +1 -1
  59. package/lib/patch-engine/patchTransport.d.ts +2 -1
  60. package/lib/patch-engine/patchTransport.js +4 -2
  61. package/lib/runtime/service.d.ts +2 -1
  62. package/lib/runtime/service.js +77 -22
  63. package/lib/scripts/bundle.js +10 -0
  64. package/lib/scripts/canonicalArtifact.d.ts +3 -0
  65. package/lib/scripts/canonicalArtifact.js +3 -1
  66. package/lib/scripts/exportProject.js +11 -0
  67. package/lib/scripts/nativeBuildNumber.d.ts +9 -0
  68. package/lib/scripts/nativeBuildNumber.js +110 -0
  69. package/lib/scripts/runtimeCompatibilityMetadata.d.ts +10 -0
  70. package/lib/scripts/runtimeCompatibilityMetadata.js +13 -0
  71. package/package.json +25 -11
  72. package/third_party/expo-fingerprint/LICENSE +22 -0
  73. package/third_party/expo-fingerprint/NOTICE +5 -0
  74. package/third_party/expo-fingerprint/PROVENANCE.md +41 -0
  75. package/third_party/expo-fingerprint/build/Config.js +122 -0
  76. package/third_party/expo-fingerprint/build/Dedup.js +89 -0
  77. package/third_party/expo-fingerprint/build/ExpoConfig.js +93 -0
  78. package/third_party/expo-fingerprint/build/ExpoConfigLoader.js +201 -0
  79. package/third_party/expo-fingerprint/build/ExpoResolver.js +84 -0
  80. package/third_party/expo-fingerprint/build/Fingerprint.js +111 -0
  81. package/third_party/expo-fingerprint/build/Fingerprint.types.js +3 -0
  82. package/third_party/expo-fingerprint/build/Options.js +140 -0
  83. package/third_party/expo-fingerprint/build/Presets.js +62 -0
  84. package/third_party/expo-fingerprint/build/ProjectWorkflow.js +163 -0
  85. package/third_party/expo-fingerprint/build/Sort.js +46 -0
  86. package/third_party/expo-fingerprint/build/hash/FileHookTransform.js +42 -0
  87. package/third_party/expo-fingerprint/build/hash/Hash.js +264 -0
  88. package/third_party/expo-fingerprint/build/hash/ReactImportsPatcher.js +344 -0
  89. package/third_party/expo-fingerprint/build/index.js +23 -0
  90. package/third_party/expo-fingerprint/build/sourcer/AutolinkingConfig.js +130 -0
  91. package/third_party/expo-fingerprint/build/sourcer/Bare.js +231 -0
  92. package/third_party/expo-fingerprint/build/sourcer/Expo.js +376 -0
  93. package/third_party/expo-fingerprint/build/sourcer/Packages.js +54 -0
  94. package/third_party/expo-fingerprint/build/sourcer/PatchPackage.js +22 -0
  95. package/third_party/expo-fingerprint/build/sourcer/SourceSkips.js +79 -0
  96. package/third_party/expo-fingerprint/build/sourcer/Sourcer.js +58 -0
  97. package/third_party/expo-fingerprint/build/sourcer/Utils.js +129 -0
  98. package/third_party/expo-fingerprint/build/types/module.d.js +2 -0
  99. package/third_party/expo-fingerprint/build/utils/Concurrency.js +47 -0
  100. package/third_party/expo-fingerprint/build/utils/Env.js +28 -0
  101. package/third_party/expo-fingerprint/build/utils/Path.js +161 -0
  102. package/third_party/expo-fingerprint/build/utils/Predicates.js +6 -0
  103. package/third_party/expo-fingerprint/build/utils/Profile.js +41 -0
  104. package/third_party/expo-fingerprint/build/utils/Spawn.js +38 -0
  105. package/third_party/expo-fingerprint/build/utils/SpawnIPC.js +28 -0
  106. package/third_party/expo-fingerprint/scheme-1-contract.json +132 -0
  107. package/third_party/expo-fingerprint/upstream-files.json +37 -0
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_PRESET = void 0;
4
+ exports.resolvePreset = resolvePreset;
5
+ const SourceSkips_1 = require("./sourcer/SourceSkips");
6
+ /**
7
+ * The preset used when a project doesn't configure one.
8
+ */
9
+ exports.DEFAULT_PRESET = 'balanced';
10
+ /**
11
+ * Resolve a preset name to the settings it stands for.
12
+ *
13
+ * - `strict`: highest fidelity - the historical default. Only skips prebuild-mutated package.json
14
+ * scripts so a fingerprint stays consistent before and after prebuild. Autolinking config is
15
+ * still sorted before hashing, so the fingerprint changes once on upgrade.
16
+ * - `balanced`: the default. Also ignores app version and string runtime version churn, the EAS
17
+ * Build files (`eas.json` and `.easignore`), and path fields in the resolved autolinking config,
18
+ * and hashes autolinked packages and node_modules config-plugin modules by their `package.json`
19
+ * version. Best first-time experience.
20
+ * - `relaxed`: for building multiple variants from one native project. Additionally ignores app
21
+ * names, bundle identifiers, schemes, and assets, while still hashing the config-plugins list so
22
+ * adding a plugin still changes the fingerprint.
23
+ */
24
+ function resolvePreset(preset) {
25
+ switch (preset) {
26
+ case 'strict':
27
+ return {
28
+ sourceSkips: SourceSkips_1.SourceSkips.PackageJsonAndroidAndIosScriptsIfNotContainRun,
29
+ nativeModuleSourceType: 'files',
30
+ configPluginSourceType: 'files',
31
+ };
32
+ case 'balanced':
33
+ return {
34
+ sourceSkips: SourceSkips_1.SourceSkips.PackageJsonAndroidAndIosScriptsIfNotContainRun |
35
+ SourceSkips_1.SourceSkips.ExpoConfigVersions |
36
+ SourceSkips_1.SourceSkips.ExpoConfigRuntimeVersionIfString |
37
+ SourceSkips_1.SourceSkips.EasJson |
38
+ SourceSkips_1.SourceSkips.Easignore |
39
+ SourceSkips_1.SourceSkips.AutolinkingConfigPaths,
40
+ nativeModuleSourceType: 'package',
41
+ configPluginSourceType: 'package',
42
+ };
43
+ case 'relaxed':
44
+ return {
45
+ sourceSkips: SourceSkips_1.SourceSkips.PackageJsonAndroidAndIosScriptsIfNotContainRun |
46
+ SourceSkips_1.SourceSkips.ExpoConfigVersions |
47
+ SourceSkips_1.SourceSkips.ExpoConfigRuntimeVersionIfString |
48
+ SourceSkips_1.SourceSkips.EasJson |
49
+ SourceSkips_1.SourceSkips.Easignore |
50
+ SourceSkips_1.SourceSkips.AutolinkingConfigPaths |
51
+ SourceSkips_1.SourceSkips.ExpoConfigNames |
52
+ SourceSkips_1.SourceSkips.ExpoConfigAndroidPackage |
53
+ SourceSkips_1.SourceSkips.ExpoConfigIosBundleIdentifier |
54
+ SourceSkips_1.SourceSkips.ExpoConfigSchemes |
55
+ SourceSkips_1.SourceSkips.ExpoConfigAssets,
56
+ nativeModuleSourceType: 'package',
57
+ configPluginSourceType: 'package',
58
+ };
59
+ default:
60
+ throw new Error(`Invalid fingerprint preset: ${preset}. Supported presets are 'strict', 'balanced', and 'relaxed'.`);
61
+ }
62
+ }
@@ -0,0 +1,163 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.resolveProjectWorkflowAsync = resolveProjectWorkflowAsync;
7
+ exports.resolveProjectWorkflowPerPlatformAsync = resolveProjectWorkflowPerPlatformAsync;
8
+ const Spawn_1 = __importDefault(require("./utils/Spawn"));
9
+ const promises_1 = __importDefault(require("fs/promises"));
10
+ const glob_1 = require("glob");
11
+ const ignore_1 = __importDefault(require("ignore"));
12
+ const path_1 = __importDefault(require("path"));
13
+ const ExpoResolver_1 = require("./ExpoResolver");
14
+ const Path_1 = require("./utils/Path");
15
+ /**
16
+ * Replicated project workflow detection logic from expo-updates:
17
+ * - https://github.com/expo/expo/blob/9b829e0749b8ff04f55a02b03cd1fefa74c5cd8d/packages/expo-updates/utils/src/workflow.ts
18
+ * - https://github.com/expo/expo/blob/9b829e0749b8ff04f55a02b03cd1fefa74c5cd8d/packages/expo-updates/utils/src/vcs.ts
19
+ */
20
+ async function resolveProjectWorkflowAsync(projectRoot, platform, fingerprintIgnorePaths) {
21
+ const configPluginsPackageRoot = (0, ExpoResolver_1.resolveExpoConfigPluginsPackagePath)(projectRoot);
22
+ if (configPluginsPackageRoot == null) {
23
+ return 'unknown';
24
+ }
25
+ const { AndroidConfig, IOSConfig } = require(configPluginsPackageRoot);
26
+ let platformWorkflowMarkers;
27
+ try {
28
+ platformWorkflowMarkers =
29
+ platform === 'android'
30
+ ? [
31
+ path_1.default.join(projectRoot, 'android/app/build.gradle'),
32
+ await AndroidConfig.Paths.getAndroidManifestAsync(projectRoot),
33
+ ]
34
+ : [IOSConfig.Paths.getPBXProjectPath(projectRoot)];
35
+ }
36
+ catch {
37
+ return 'managed';
38
+ }
39
+ const vcsClient = await getVCSClientAsync(projectRoot);
40
+ const vcsRoot = path_1.default.normalize(await vcsClient.getRootPathAsync());
41
+ for (const marker of platformWorkflowMarkers) {
42
+ const relativeMarker = (0, Path_1.toPosixPath)(path_1.default.relative(vcsRoot, marker));
43
+ if ((await (0, Path_1.pathExistsAsync)(marker)) &&
44
+ !(0, Path_1.isIgnoredPathWithMatchObjects)(relativeMarker, fingerprintIgnorePaths) &&
45
+ !(await vcsClient.isFileIgnoredAsync(relativeMarker))) {
46
+ return 'generic';
47
+ }
48
+ }
49
+ return 'managed';
50
+ }
51
+ async function resolveProjectWorkflowPerPlatformAsync(projectRoot, fingerprintIgnorePaths) {
52
+ const [android, ios] = await Promise.all([
53
+ resolveProjectWorkflowAsync(projectRoot, 'android', fingerprintIgnorePaths),
54
+ resolveProjectWorkflowAsync(projectRoot, 'ios', fingerprintIgnorePaths),
55
+ ]);
56
+ return { android, ios };
57
+ }
58
+ async function getVCSClientAsync(projectRoot) {
59
+ if (await isGitInstalledAndConfiguredAsync(projectRoot)) {
60
+ return new GitClient(projectRoot);
61
+ }
62
+ else {
63
+ return new NoVCSClient(projectRoot);
64
+ }
65
+ }
66
+ class GitClient {
67
+ constructor(projectRoot) {
68
+ this.projectRoot = projectRoot;
69
+ }
70
+ async getRootPathAsync() {
71
+ return (await (0, Spawn_1.default)('git', ['rev-parse', '--show-toplevel'], { cwd: this.projectRoot })).stdout.trim();
72
+ }
73
+ async isFileIgnoredAsync(filePath) {
74
+ try {
75
+ await (0, Spawn_1.default)('git', ['check-ignore', '-q', filePath], {
76
+ cwd: path_1.default.normalize(await this.getRootPathAsync()),
77
+ });
78
+ return true;
79
+ }
80
+ catch {
81
+ return false;
82
+ }
83
+ }
84
+ }
85
+ class NoVCSClient {
86
+ constructor(projectRoot) {
87
+ this.projectRoot = projectRoot;
88
+ }
89
+ async getRootPathAsync() {
90
+ return this.projectRoot;
91
+ }
92
+ async isFileIgnoredAsync(filePath) {
93
+ const ignore = new Ignore(this.projectRoot);
94
+ await ignore.initIgnoreAsync();
95
+ return ignore.ignores(filePath);
96
+ }
97
+ }
98
+ async function isGitInstalledAndConfiguredAsync(projectRoot) {
99
+ try {
100
+ await (0, Spawn_1.default)('git', ['--help']);
101
+ }
102
+ catch (error) {
103
+ if (error.code === 'ENOENT') {
104
+ return false;
105
+ }
106
+ throw error;
107
+ }
108
+ try {
109
+ await (0, Spawn_1.default)('git', ['rev-parse', '--show-toplevel'], { cwd: projectRoot });
110
+ }
111
+ catch {
112
+ return false;
113
+ }
114
+ return true;
115
+ }
116
+ const GITIGNORE_FILENAME = '.gitignore';
117
+ const DEFAULT_IGNORE = `
118
+ .git
119
+ node_modules
120
+ `;
121
+ /**
122
+ * Ignore wraps the 'ignore' package to support multiple .gitignore files
123
+ * in subdirectories.
124
+ *
125
+ * Inconsistencies with git behavior:
126
+ * - if parent .gitignore has ignore rule and child has exception to that rule,
127
+ * file will still be ignored,
128
+ * - node_modules is always ignored
129
+ *
130
+ * Differs from the eas-cli Ignore class by not using `.easignore`. Otherwise this is copied. May try
131
+ * to merge the implementations soon.
132
+ */
133
+ class Ignore {
134
+ constructor(rootDir) {
135
+ this.rootDir = rootDir;
136
+ this.ignoreMapping = [];
137
+ }
138
+ async initIgnoreAsync() {
139
+ const ignoreFilePaths = (await (0, glob_1.glob)(`**/${GITIGNORE_FILENAME}`, {
140
+ cwd: this.rootDir,
141
+ ignore: ['node_modules'],
142
+ follow: false,
143
+ }))
144
+ // ensure that parent dir is before child directories
145
+ .sort((a, b) => a.length - b.length && a.localeCompare(b));
146
+ const ignoreMapping = await Promise.all(ignoreFilePaths.map(async (filePath) => {
147
+ return [
148
+ filePath.slice(0, filePath.length - GITIGNORE_FILENAME.length),
149
+ (0, ignore_1.default)().add(await promises_1.default.readFile(path_1.default.join(this.rootDir, filePath), 'utf-8')),
150
+ ];
151
+ }));
152
+ this.ignoreMapping = [['', (0, ignore_1.default)().add(DEFAULT_IGNORE)], ...ignoreMapping];
153
+ }
154
+ ignores(relativePath) {
155
+ for (const [prefix, ignore] of this.ignoreMapping) {
156
+ if (relativePath.startsWith(prefix) && ignore.ignores(relativePath.slice(prefix.length))) {
157
+ return true;
158
+ }
159
+ }
160
+ return false;
161
+ }
162
+ }
163
+ //#endregion - a copy of vcs client and ignore handler from expo-updates
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sortSources = sortSources;
4
+ exports.compareSource = compareSource;
5
+ const compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
6
+ function sortSources(sources) {
7
+ return sources.sort(compareSource);
8
+ }
9
+ const typeOrder = {
10
+ file: 0,
11
+ dir: 1,
12
+ contents: 2,
13
+ package: 3,
14
+ };
15
+ /**
16
+ * Comparator between two sources.
17
+ * This is useful for sorting sources in a consistent order.
18
+ * @returns:
19
+ * == 0 if a and b are equal,
20
+ * < 0 if a is less than b,
21
+ * > 0 if a is greater than b.
22
+ */
23
+ function compareSource(a, b) {
24
+ const typeResult = typeOrder[a.type] - typeOrder[b.type];
25
+ if (typeResult === 0) {
26
+ if (a.type === 'file' && b.type === 'file') {
27
+ const aValue = a.overrideHashKey ?? a.filePath;
28
+ const bValue = b.overrideHashKey ?? b.filePath;
29
+ return compareText(aValue, bValue);
30
+ }
31
+ else if (a.type === 'dir' && b.type === 'dir') {
32
+ const aValue = a.overrideHashKey ?? a.filePath;
33
+ const bValue = b.overrideHashKey ?? b.filePath;
34
+ return compareText(aValue, bValue);
35
+ }
36
+ else if (a.type === 'contents' && b.type === 'contents') {
37
+ return compareText(a.id, b.id);
38
+ }
39
+ else if (a.type === 'package' && b.type === 'package') {
40
+ const aValue = a.overrideHashKey ?? `${a.name}@${a.version}`;
41
+ const bValue = b.overrideHashKey ?? `${b.name}@${b.version}`;
42
+ return compareText(aValue, bValue);
43
+ }
44
+ }
45
+ return typeResult;
46
+ }
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FileHookTransform = void 0;
4
+ const stream_1 = require("stream");
5
+ /**
6
+ * A transform stream that allows to hook into file contents and transform them.
7
+ */
8
+ class FileHookTransform extends stream_1.Transform {
9
+ constructor(source, transformFn, debug) {
10
+ super();
11
+ this.source = source;
12
+ this.transformFn = transformFn;
13
+ this.debug = debug;
14
+ this._isTransformed = undefined;
15
+ }
16
+ /**
17
+ * Indicates whether the file content has been transformed.
18
+ * @returns boolean value if `debug` is true, otherwise the value would be undefined.
19
+ */
20
+ get isTransformed() {
21
+ return this._isTransformed;
22
+ }
23
+ //#region - Transform implementations
24
+ _transform(chunk, encoding, callback) {
25
+ const result = this.transformFn(this.source, chunk, false /* isEndOfFile */, encoding);
26
+ if (this.debug) {
27
+ this._isTransformed || (this._isTransformed = chunk !== result);
28
+ }
29
+ if (result) {
30
+ this.push(result);
31
+ }
32
+ callback();
33
+ }
34
+ _flush(callback) {
35
+ const result = this.transformFn(this.source, null, true /* isEndOfFile */, 'utf8');
36
+ if (result) {
37
+ this.push(result);
38
+ }
39
+ callback();
40
+ }
41
+ }
42
+ exports.FileHookTransform = FileHookTransform;
@@ -0,0 +1,264 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createFingerprintFromSourcesAsync = createFingerprintFromSourcesAsync;
7
+ exports.createFingerprintSourceAsync = createFingerprintSourceAsync;
8
+ exports.createFileHashResultsAsync = createFileHashResultsAsync;
9
+ exports.createDirHashResultsAsync = createDirHashResultsAsync;
10
+ exports.createContentsHashResultsAsync = createContentsHashResultsAsync;
11
+ exports.createPackageHashResultsAsync = createPackageHashResultsAsync;
12
+ exports.createSourceId = createSourceId;
13
+ const crypto_1 = require("crypto");
14
+ const fs_1 = require("fs");
15
+ const promises_1 = __importDefault(require("fs/promises"));
16
+ const path_1 = __importDefault(require("path"));
17
+ const stream_1 = require("stream");
18
+ const Concurrency_1 = require("../utils/Concurrency");
19
+ const Path_1 = require("../utils/Path");
20
+ const Predicates_1 = require("../utils/Predicates");
21
+ const Profile_1 = require("../utils/Profile");
22
+ const FileHookTransform_1 = require("./FileHookTransform");
23
+ const ReactImportsPatcher_1 = require("./ReactImportsPatcher");
24
+ /**
25
+ * Create a `Fingerprint` from `HashSources` array
26
+ */
27
+ async function createFingerprintFromSourcesAsync(sources, projectRoot, options) {
28
+ const limiter = (0, Concurrency_1.createLimiter)(options.concurrentIoLimit);
29
+ const fingerprintSources = await Promise.all(sources.map((source) => createFingerprintSourceAsync(source, limiter, projectRoot, options)));
30
+ const hasher = (0, crypto_1.createHash)(options.hashAlgorithm);
31
+ for (const source of fingerprintSources) {
32
+ if (source.hash != null) {
33
+ hasher.update(createSourceId(source));
34
+ hasher.update(source.hash);
35
+ }
36
+ }
37
+ const hash = hasher.digest('hex');
38
+ return {
39
+ sources: fingerprintSources,
40
+ hash,
41
+ };
42
+ }
43
+ /**
44
+ * Create a `FingerprintSource` from a `HashSource`
45
+ * This function will get a hash value and merge back to original source
46
+ */
47
+ async function createFingerprintSourceAsync(source, limiter, projectRoot, options) {
48
+ let result = null;
49
+ switch (source.type) {
50
+ case 'contents':
51
+ result = await createContentsHashResultsAsync(source, options);
52
+ break;
53
+ case 'file':
54
+ result = await createFileHashResultsAsync(source.filePath, limiter, projectRoot, options);
55
+ break;
56
+ case 'dir':
57
+ result = await (0, Profile_1.profile)(options, createDirHashResultsAsync, `createDirHashResultsAsync(${source.filePath})`)(source.filePath, limiter, projectRoot, options);
58
+ break;
59
+ case 'package':
60
+ result = await createPackageHashResultsAsync(source, options);
61
+ break;
62
+ default:
63
+ throw new Error('Unsupported source type');
64
+ }
65
+ return {
66
+ ...source,
67
+ hash: result?.hex ?? null,
68
+ ...(options.debug ? { debugInfo: result?.debugInfo } : undefined),
69
+ };
70
+ }
71
+ /**
72
+ * Create a `HashResult` from a file
73
+ */
74
+ async function createFileHashResultsAsync(filePath, limiter, projectRoot, options) {
75
+ // Backup code for faster hashing
76
+ /*
77
+ return limiter(async () => {
78
+ if (isIgnoredPathWithMatchObjects(filePath, options.ignorePathMatchObjects)) {
79
+ return null;
80
+ }
81
+
82
+ const hasher = createHash(options.hashAlgorithm);
83
+
84
+ const stat = await fs.stat(filePath);
85
+ hasher.update(`${stat.size}`);
86
+
87
+ const buffer = Buffer.alloc(4096);
88
+ const fd = await fs.open(filePath, 'r');
89
+ await fd.read(buffer, 0, buffer.length, 0);
90
+ await fd.close();
91
+ hasher.update(buffer);
92
+ console.log('stat', filePath, stat.size);
93
+ return { id: path.relative(projectRoot, filePath), hex: hasher.digest('hex') };
94
+ });
95
+ */
96
+ return limiter(() => {
97
+ return new Promise((resolve, reject) => {
98
+ if ((0, Path_1.isIgnoredPathWithMatchObjects)(filePath, options.ignorePathMatchObjects)) {
99
+ return resolve(null);
100
+ }
101
+ let resolved = false;
102
+ const hasher = (0, crypto_1.createHash)(options.hashAlgorithm);
103
+ const fileHookTransform = options.fileHookTransform
104
+ ? new FileHookTransform_1.FileHookTransform({ type: 'file', filePath }, options.fileHookTransform, options.debug)
105
+ : null;
106
+ let stream = (0, fs_1.createReadStream)(path_1.default.join(projectRoot, filePath), {
107
+ highWaterMark: 1024,
108
+ });
109
+ if (options.enableReactImportsPatcher &&
110
+ (filePath.endsWith('.h') || filePath.endsWith('.m') || filePath.endsWith('.mm'))) {
111
+ const transform = new ReactImportsPatcher_1.ReactImportsPatchTransform();
112
+ stream = (0, stream_1.pipeline)(stream, transform, (err) => {
113
+ if (err) {
114
+ reject(err);
115
+ }
116
+ });
117
+ }
118
+ if (fileHookTransform) {
119
+ stream = (0, stream_1.pipeline)(stream, fileHookTransform, (err) => {
120
+ if (err) {
121
+ reject(err);
122
+ }
123
+ });
124
+ }
125
+ stream.on('close', () => {
126
+ if (!resolved) {
127
+ const hex = hasher.digest('hex');
128
+ const isTransformed = fileHookTransform?.isTransformed;
129
+ const debugInfo = options.debug
130
+ ? {
131
+ path: filePath,
132
+ hash: hex,
133
+ ...(isTransformed ? { isTransformed } : undefined),
134
+ }
135
+ : undefined;
136
+ resolve({
137
+ type: 'file',
138
+ id: filePath,
139
+ hex,
140
+ ...(debugInfo ? { debugInfo } : undefined),
141
+ });
142
+ resolved = true;
143
+ }
144
+ });
145
+ stream.on('error', (e) => {
146
+ reject(e);
147
+ });
148
+ stream.on('data', (chunk) => {
149
+ hasher.update(chunk);
150
+ });
151
+ });
152
+ });
153
+ }
154
+ /**
155
+ * Create `HashResult` for a dir.
156
+ * If the dir is excluded, returns null rather than a HashResult
157
+ */
158
+ async function createDirHashResultsAsync(dirPath, limiter, projectRoot, options, depth = 0) {
159
+ // Using `ignoreDirMatchObjects` as an optimization to skip the whole directory
160
+ if ((0, Path_1.isIgnoredPathWithMatchObjects)(dirPath, options.ignoreDirMatchObjects)) {
161
+ return null;
162
+ }
163
+ const dirents = (await promises_1.default.readdir(path_1.default.join(projectRoot, dirPath), { withFileTypes: true })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
164
+ const results = (await Promise.all(dirents.map(async (dirent) => {
165
+ if (dirent.isDirectory()) {
166
+ // Skip nested node_modules inside a package.
167
+ if (dirent.name === 'node_modules') {
168
+ return null;
169
+ }
170
+ const filePath = (0, Path_1.toPosixPath)(path_1.default.join(dirPath, dirent.name));
171
+ return await createDirHashResultsAsync(filePath, limiter, projectRoot, options, depth + 1);
172
+ }
173
+ else if (dirent.isFile()) {
174
+ const filePath = (0, Path_1.toPosixPath)(path_1.default.join(dirPath, dirent.name));
175
+ return await createFileHashResultsAsync(filePath, limiter, projectRoot, options);
176
+ }
177
+ return null;
178
+ }))).filter(Predicates_1.nonNullish);
179
+ if (results.length === 0) {
180
+ return null;
181
+ }
182
+ const hasher = (0, crypto_1.createHash)(options.hashAlgorithm);
183
+ const children = [];
184
+ for (const result of results) {
185
+ hasher.update(result.id);
186
+ hasher.update(result.hex);
187
+ children.push(result.debugInfo);
188
+ }
189
+ const hex = hasher.digest('hex');
190
+ return {
191
+ type: 'dir',
192
+ id: dirPath,
193
+ hex,
194
+ ...(options.debug ? { debugInfo: { path: dirPath, children, hash: hex } } : undefined),
195
+ };
196
+ }
197
+ /**
198
+ * Create `HashResult` for a `HashSourceContents`
199
+ */
200
+ async function createContentsHashResultsAsync(source, options) {
201
+ let isTransformed = undefined;
202
+ if (options.fileHookTransform) {
203
+ const transformedContents = options.fileHookTransform({
204
+ type: 'contents',
205
+ id: source.id,
206
+ }, source.contents, true /* isEndOfFile */, 'utf8') ?? '';
207
+ if (options.debug) {
208
+ isTransformed = transformedContents !== source.contents;
209
+ }
210
+ source.contents = transformedContents;
211
+ }
212
+ const hex = (0, crypto_1.createHash)(options.hashAlgorithm).update(source.contents).digest('hex');
213
+ const debugInfo = options.debug
214
+ ? {
215
+ hash: hex,
216
+ ...(isTransformed ? { isTransformed } : undefined),
217
+ }
218
+ : undefined;
219
+ return {
220
+ type: 'contents',
221
+ id: source.id,
222
+ hex,
223
+ ...(debugInfo ? { debugInfo } : undefined),
224
+ };
225
+ }
226
+ /**
227
+ * Create a `HashResult` for a package from its embedded `name` and `version`.
228
+ * The sourcer reads these from the `package.json`, so the hash depends on the package identity
229
+ * rather than its resolved path or unrelated contents.
230
+ * Returns null when the package is ignored.
231
+ */
232
+ async function createPackageHashResultsAsync(source, options) {
233
+ if ((0, Path_1.isIgnoredPathWithMatchObjects)(source.filePath, options.ignorePathMatchObjects)) {
234
+ return null;
235
+ }
236
+ const { name, version } = source;
237
+ const hex = (0, crypto_1.createHash)(options.hashAlgorithm)
238
+ .update(JSON.stringify({ name, version }))
239
+ .digest('hex');
240
+ const debugInfo = options.debug ? { path: source.filePath, name, version, hash: hex } : undefined;
241
+ return {
242
+ type: 'package',
243
+ id: createSourceId(source),
244
+ hex,
245
+ ...(debugInfo ? { debugInfo } : undefined),
246
+ };
247
+ }
248
+ /**
249
+ * Create id from given source
250
+ */
251
+ function createSourceId(source) {
252
+ switch (source.type) {
253
+ case 'contents':
254
+ return source.id;
255
+ case 'file':
256
+ return source.overrideHashKey ?? source.filePath;
257
+ case 'dir':
258
+ return source.overrideHashKey ?? source.filePath;
259
+ case 'package':
260
+ return source.overrideHashKey ?? `${source.name}@${source.version}`;
261
+ default:
262
+ throw new Error('Unsupported source type');
263
+ }
264
+ }