@gfean/react-native-bundle-drop 0.9.0 → 0.11.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 +77 -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 +12 -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 +3 -0
  22. package/lib/CLI/scripts/upload-cli.js +239 -107
  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 +26 -12
  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,116 @@
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.collectNativeFingerprint = collectNativeFingerprint;
7
+ const crypto_1 = __importDefault(require("crypto"));
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const path_1 = __importDefault(require("path"));
10
+ const config_1 = require("./config");
11
+ const normalizeBuildNumber_1 = require("./normalizeBuildNumber");
12
+ const normalizeIosBuildNumber_1 = require("./normalizeIosBuildNumber");
13
+ // The complete maintained adaptation is packaged independently of the mobile SDK.
14
+ const upstreamRoot = path_1.default.resolve(__dirname, '..', '..', 'third_party', 'expo-fingerprint', 'build');
15
+ const upstream = (file) => require(path_1.default.join(upstreamRoot, file));
16
+ const GENERATED_PATHS = [
17
+ '**/.bundle-drop/generated/**', '**/.bundle-drop/artifacts/**',
18
+ '**/.bundle-drop/fingerprints/**', '**/.bundle-drop/build-identity.json',
19
+ '**/.bundle-drop/runtime-delivery.lock.json', '**/.bundle-drop/runtime-delivery.generated.json',
20
+ '**/bundle.drop.config.js',
21
+ '**/node_modules/@gfean/react-native-bundle-drop/dist/**',
22
+ '**/*-gradle-plugin/.kotlin/**', '**/android/.kotlin/**', '**/android/local.properties',
23
+ '**/android/**/debug.keystore', '**/android/**/output-metadata.json',
24
+ ];
25
+ function extraSources(projectRoot, platform, entries) {
26
+ const ids = new Set();
27
+ return entries.flatMap(entry => {
28
+ if (!entry || typeof entry.id !== 'string' || !entry.id.trim() ||
29
+ typeof entry.value !== 'string' || !entry.value ||
30
+ !['file', 'dir', 'environment'].includes(entry.type)) {
31
+ throw new Error('Invalid fingerprint extra source. Supply id, type, and value.');
32
+ }
33
+ if (ids.has(entry.id))
34
+ throw new Error(`Duplicate fingerprint extra source: ${entry.id}`);
35
+ ids.add(entry.id);
36
+ if (entry.platforms && !entry.platforms.includes(platform))
37
+ return [];
38
+ const value = entry.type === 'environment' ? process.env[entry.value] : path_1.default.resolve(projectRoot, entry.value);
39
+ const present = entry.type === 'environment' ? value !== undefined : fs_1.default.existsSync(value);
40
+ if (!present) {
41
+ if (!entry.optional)
42
+ throw new Error(`Required fingerprint extra source is missing: ${entry.id}`);
43
+ return [{ type: 'contents', id: `extra:${entry.id}`, contents: 'absent', reasons: ['explicitOptionalInput'] }];
44
+ }
45
+ if (entry.type === 'environment') {
46
+ return [{ type: 'contents', id: `extra:${entry.id}`, contents: JSON.stringify({ value }), reasons: ['explicitEnvironment'] }];
47
+ }
48
+ const stat = fs_1.default.statSync(value);
49
+ if ((entry.type === 'file' && !stat.isFile()) || (entry.type === 'dir' && !stat.isDirectory())) {
50
+ throw new Error(`Fingerprint extra source has the wrong type: ${entry.id}`);
51
+ }
52
+ return [{ type: entry.type, filePath: path_1.default.relative(projectRoot, value).split(path_1.default.sep).join('/'),
53
+ overrideHashKey: `extra:${entry.id}`, reasons: ['explicitNativeInput'] }];
54
+ });
55
+ }
56
+ /** Each call collects fresh source inputs; receipts and previous reports are never read. */
57
+ async function collectNativeFingerprint(projectRoot, platform) {
58
+ // Config modules are resolved by Node to physical paths. Use the same root
59
+ // for source IDs so a checkout symlink cannot change the native identity.
60
+ projectRoot = fs_1.default.realpathSync(path_1.default.resolve(projectRoot));
61
+ const configPath = path_1.default.join(projectRoot, 'bundle.drop.config.js');
62
+ delete require.cache[require.resolve(configPath)];
63
+ const config = require(configPath);
64
+ const selected = (0, config_1.selectRuntimeVersion)(config.runtimeVersion, platform);
65
+ if (selected.source !== 'fingerprint')
66
+ throw new Error('Fingerprint collection requires compatibilitySource: fingerprint.');
67
+ const mode = selected.options.nativeProjectMode?.[platform];
68
+ if (mode === 'native' && !fs_1.default.statSync(path_1.default.join(projectRoot, platform)).isDirectory()) {
69
+ throw new Error(`The selected native fingerprint project is missing ${platform}/.`);
70
+ }
71
+ const bufferedFiles = new Map();
72
+ const options = await upstream('Options').normalizeOptionsAsync(projectRoot, {
73
+ platforms: [platform], preset: 'strict', hashAlgorithm: 'sha256', concurrentIoLimit: 8,
74
+ nativeModuleSourceType: 'files', configPluginSourceType: 'files',
75
+ bundleDropNativeProjectMode: selected.options.nativeProjectMode,
76
+ sourceSkips: upstream('sourcer/SourceSkips').SourceSkips.PackageJsonAndroidAndIosScriptsIfNotContainRun |
77
+ upstream('sourcer/SourceSkips').SourceSkips.ExpoConfigVersions |
78
+ upstream('sourcer/SourceSkips').SourceSkips.GitIgnore,
79
+ ignorePaths: GENERATED_PATHS,
80
+ extraSources: extraSources(projectRoot, platform, selected.options.extraSources ?? []),
81
+ debug: true, silent: true,
82
+ fileHookTransform: (source, chunk, isEnd) => {
83
+ const normalize = /\.gradle(?:\.kts)?$/.test(source.filePath) ? normalizeBuildNumber_1.normalizeAndroidBuildNumber
84
+ : /^ios\/[^/]+\.xcodeproj\/project\.pbxproj$/.test(source.filePath) ? normalizeIosBuildNumber_1.normalizeIosProjectBuildNumber : null;
85
+ if (source.type !== 'file' || !normalize)
86
+ return chunk;
87
+ const chunks = bufferedFiles.get(source.filePath) ?? [];
88
+ if (chunk)
89
+ chunks.push(Buffer.from(chunk));
90
+ if (!isEnd) {
91
+ bufferedFiles.set(source.filePath, chunks);
92
+ return null;
93
+ }
94
+ bufferedFiles.delete(source.filePath);
95
+ return normalize(Buffer.concat(chunks).toString('utf8'));
96
+ },
97
+ });
98
+ if (!options.useCNGForPlatforms[platform] && !fs_1.default.existsSync(path_1.default.join(projectRoot, platform))) {
99
+ throw new Error(`Required native fingerprint directory is missing: ${platform}/.`);
100
+ }
101
+ const collected = await upstream('sourcer/Sourcer').getHashSourcesAsync(projectRoot, options);
102
+ const sources = upstream('Sort').sortSources(upstream('Dedup').dedupSources(collected, projectRoot));
103
+ const fingerprint = await upstream('hash/Hash').createFingerprintFromSourcesAsync(sources, projectRoot, options);
104
+ const runtimeVersion = `bdfp1-${crypto_1.default.createHash('sha256').update(JSON.stringify({
105
+ domain: 'bundle-drop-native-fingerprint', schemeVersion: 1, platform,
106
+ manualBoundary: selected.boundary, nativeHash: fingerprint.hash,
107
+ })).digest('hex')}`;
108
+ return {
109
+ status: 'stable', schemeVersion: 1, platform, runtimeVersion,
110
+ nativeHash: fingerprint.hash, manualBoundary: selected.boundary,
111
+ sources: fingerprint.sources.map((source) => ({
112
+ type: source.type, id: upstream('hash/Hash').createSourceId(source),
113
+ hash: source.hash, reasons: source.reasons, debugInfo: source.debugInfo,
114
+ })),
115
+ };
116
+ }
@@ -0,0 +1,14 @@
1
+ import type { FingerprintOptions } from './types';
2
+ type RuntimeSelection = {
3
+ source: 'manual';
4
+ runtimeVersion: string;
5
+ } | {
6
+ source: 'expo';
7
+ } | {
8
+ source: 'fingerprint';
9
+ boundary: string | null;
10
+ options: FingerprintOptions;
11
+ };
12
+ /** Validate selectors once, independently of Expo/project detection. */
13
+ export declare function selectRuntimeVersion(value: unknown, platform: 'ios' | 'android'): RuntimeSelection;
14
+ export {};
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.selectRuntimeVersion = selectRuntimeVersion;
4
+ /** Validate selectors once, independently of Expo/project detection. */
5
+ function selectRuntimeVersion(value, platform) {
6
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
7
+ throw new Error(`bundle.drop.config.js must define runtimeVersion.${platform}.`);
8
+ }
9
+ const config = value;
10
+ if (config.source !== undefined) {
11
+ if (config.source !== 'expo')
12
+ throw new Error('Unsupported runtimeVersion.source.');
13
+ if (['compatibilitySource', 'fingerprint', 'ios', 'android'].some(key => config[key] !== undefined)) {
14
+ throw new Error('runtimeVersion.source: expo cannot be combined with compatibilitySource, fingerprint options, or platform literals.');
15
+ }
16
+ return { source: 'expo' };
17
+ }
18
+ if (config.compatibilitySource !== undefined && config.compatibilitySource !== 'manual' && config.compatibilitySource !== 'fingerprint') {
19
+ throw new Error('Unsupported runtimeVersion.compatibilitySource.');
20
+ }
21
+ if (config.compatibilitySource === 'fingerprint') {
22
+ for (const name of ['ios', 'android']) {
23
+ const boundary = config[name];
24
+ if (boundary !== undefined && (typeof boundary !== 'string' || !boundary.trim())) {
25
+ throw new Error(`Fingerprint runtimeVersion.${name} must be a non-empty literal or omitted.`);
26
+ }
27
+ }
28
+ const options = config.fingerprint ?? {};
29
+ if (!options || typeof options !== 'object' || Array.isArray(options)) {
30
+ throw new Error('runtimeVersion.fingerprint must be an object.');
31
+ }
32
+ const typed = options;
33
+ if (Object.keys(options).some(key => !['schemeVersion', 'nativeProjectMode', 'extraSources'].includes(key))) {
34
+ throw new Error('Unsupported runtimeVersion.fingerprint option.');
35
+ }
36
+ if (typed.schemeVersion !== undefined && typed.schemeVersion !== 1) {
37
+ throw new Error('Unsupported fingerprint scheme. Only scheme 1 is available.');
38
+ }
39
+ if (typed.nativeProjectMode !== undefined) {
40
+ if (!typed.nativeProjectMode || typeof typed.nativeProjectMode !== 'object' || Array.isArray(typed.nativeProjectMode)) {
41
+ throw new Error('fingerprint.nativeProjectMode must be a platform map.');
42
+ }
43
+ for (const mode of Object.values(typed.nativeProjectMode)) {
44
+ if (mode !== 'native' && mode !== 'cng')
45
+ throw new Error('Unsupported fingerprint nativeProjectMode.');
46
+ }
47
+ }
48
+ if (typed.extraSources !== undefined && !Array.isArray(typed.extraSources)) {
49
+ throw new Error('fingerprint.extraSources must be an array.');
50
+ }
51
+ return { source: 'fingerprint', boundary: config[platform]?.trim() ?? null, options: typed };
52
+ }
53
+ if (config.fingerprint !== undefined)
54
+ throw new Error('Fingerprint options require compatibilitySource: fingerprint.');
55
+ const literal = config[platform];
56
+ if (typeof literal !== 'string' || !literal.trim()) {
57
+ throw new Error(`bundle.drop.config.js must define a non-empty runtimeVersion.${platform} literal. Use runtimeVersion: { source: 'expo' } only when explicitly opting into Expo runtime policies.`);
58
+ }
59
+ return { source: 'manual', runtimeVersion: literal.trim() };
60
+ }
@@ -0,0 +1,4 @@
1
+ /** Only normalize literal `versionCode 1` / `versionCode = 1` statements inside
2
+ * defaultConfig or a productFlavors block. All ambiguous expressions stay intact.
3
+ */
4
+ export declare function normalizeAndroidBuildNumber(source: string): string;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeAndroidBuildNumber = normalizeAndroidBuildNumber;
4
+ /** Tokenize enough Groovy/Kotlin to distinguish code from comments and strings.
5
+ * This deliberately does not evaluate expressions or interpret build scripts.
6
+ */
7
+ function tokenize(source) {
8
+ const tokens = [];
9
+ const pattern = /\/\*[\s\S]*?\*\/|\/\/[^\r\n]*|"""[\s\S]*?"""|'''[\s\S]*?'''|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[A-Za-z_$][\w$]*|\d+(?:[A-Za-z_][\w]*)?|\r?\n|[^\s]/g;
10
+ for (const match of source.matchAll(pattern)) {
11
+ const text = match[0];
12
+ if (text.startsWith('//') || text.startsWith('/*'))
13
+ continue;
14
+ tokens.push({ text, start: match.index, end: match.index + text.length });
15
+ }
16
+ return tokens;
17
+ }
18
+ /** Only normalize literal `versionCode 1` / `versionCode = 1` statements inside
19
+ * defaultConfig or a productFlavors block. All ambiguous expressions stay intact.
20
+ */
21
+ function normalizeAndroidBuildNumber(source) {
22
+ const tokens = tokenize(source);
23
+ // Slashy strings and incomplete literals are outside the recognized grammar.
24
+ if (tokens.some(token => ['/', '"', "'"].includes(token.text)))
25
+ return source;
26
+ const scopes = [];
27
+ const replacements = [];
28
+ for (let index = 0; index < tokens.length; index++) {
29
+ const token = tokens[index];
30
+ if (token.text === '{') {
31
+ scopes.push(tokens[index - 1]?.text ?? '');
32
+ }
33
+ else if (token.text === '}') {
34
+ scopes.pop();
35
+ }
36
+ else if (token.text === 'versionCode' && (scopes.includes('defaultConfig') || scopes.includes('productFlavors'))) {
37
+ const before = tokens[index - 1]?.text;
38
+ const numberIndex = index + (tokens[index + 1]?.text === '=' ? 2 : 1);
39
+ const number = tokens[numberIndex];
40
+ const after = tokens[numberIndex + 1]?.text;
41
+ const nextLineToken = tokens.slice(numberIndex + 1).find(candidate => !['\n', '\r\n'].includes(candidate.text))?.text;
42
+ const hasContinuation = ['\n', '\r\n'].includes(after) &&
43
+ ['+', '-', '*', '%', '.', '?', ':', '(', '[', '{', '&', '|', '^', '<', '>', '=', '!', ','].includes(nextLineToken ?? '');
44
+ if (['\n', '\r\n', '{', ';'].includes(before) && /^\d+$/.test(number?.text ?? '') &&
45
+ (after === undefined || ['\n', '\r\n', ';', '}'].includes(after)) && !hasContinuation) {
46
+ replacements.push(number);
47
+ }
48
+ }
49
+ }
50
+ let result = source;
51
+ for (const token of replacements.reverse()) {
52
+ result = result.slice(0, token.start) + '<bundle-drop-build-number>' + result.slice(token.end);
53
+ }
54
+ return result;
55
+ }
@@ -0,0 +1,4 @@
1
+ /** Normalize only numeric CURRENT_PROJECT_VERSION literals in buildSettings.
2
+ * Expressions, conditional keys, comments and other fields retain their bytes.
3
+ */
4
+ export declare function normalizeIosProjectBuildNumber(source: string): string;
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeIosProjectBuildNumber = normalizeIosProjectBuildNumber;
4
+ /** A lexer for the small OpenStep dictionary form written by Xcode. */
5
+ function tokenize(source) {
6
+ const tokens = [];
7
+ const pattern = /\s+|"(?:\\.|[^"\\])*"|[{}=;(),]|[^\s{}=;(),"]+/gy;
8
+ let cursor = 0;
9
+ while (cursor < source.length) {
10
+ if (source.startsWith('/*', cursor)) {
11
+ const end = source.indexOf('*/', cursor + 2);
12
+ if (end < 0)
13
+ return null;
14
+ cursor = end + 2;
15
+ continue;
16
+ }
17
+ if (source.startsWith('//', cursor)) {
18
+ const end = source.indexOf('\n', cursor + 2);
19
+ cursor = end < 0 ? source.length : end;
20
+ continue;
21
+ }
22
+ pattern.lastIndex = cursor;
23
+ const match = pattern.exec(source);
24
+ if (!match)
25
+ return null;
26
+ cursor = pattern.lastIndex;
27
+ if (!/^\s+$/.test(match[0]))
28
+ tokens.push({ text: match[0], start: match.index, end: cursor });
29
+ }
30
+ return tokens;
31
+ }
32
+ /** Normalize only numeric CURRENT_PROJECT_VERSION literals in buildSettings.
33
+ * Expressions, conditional keys, comments and other fields retain their bytes.
34
+ */
35
+ function normalizeIosProjectBuildNumber(source) {
36
+ const tokens = tokenize(source);
37
+ if (!tokens)
38
+ return source;
39
+ const scopes = [];
40
+ const replacements = [];
41
+ for (let index = 0; index < tokens.length; index++) {
42
+ const token = tokens[index];
43
+ if (token.text === '{') {
44
+ scopes.push(tokens[index - 1]?.text === '=' && tokens[index - 2]?.text === 'buildSettings' ? 'buildSettings' : '');
45
+ }
46
+ else if (token.text === '}') {
47
+ scopes.pop();
48
+ }
49
+ else if (token.text === 'CURRENT_PROJECT_VERSION' && scopes[scopes.length - 1] === 'buildSettings' &&
50
+ tokens[index + 1]?.text === '=' && tokens[index + 3]?.text === ';') {
51
+ const value = tokens[index + 2];
52
+ if (/^(?:\d+(?:\.\d+){0,2}|"\d+(?:\.\d+){0,2}")$/.test(value.text))
53
+ replacements.push(value);
54
+ }
55
+ }
56
+ let result = source;
57
+ for (const token of replacements.reverse()) {
58
+ const marker = token.text.startsWith('"') ? '"<bundle-drop-build-number>"' : '<bundle-drop-build-number>';
59
+ result = result.slice(0, token.start) + marker + result.slice(token.end);
60
+ }
61
+ return result;
62
+ }
@@ -0,0 +1,29 @@
1
+ export type FingerprintExtraSource = {
2
+ id: string;
3
+ type: 'file' | 'dir' | 'environment';
4
+ value: string;
5
+ platforms?: ('ios' | 'android')[];
6
+ optional?: boolean;
7
+ };
8
+ export type FingerprintOptions = {
9
+ /** Frozen scheme 1. Calculation changes require a new scheme version. */
10
+ schemeVersion?: 1;
11
+ nativeProjectMode?: Partial<Record<'ios' | 'android', 'native' | 'cng'>>;
12
+ extraSources?: FingerprintExtraSource[];
13
+ };
14
+ export type FingerprintSourceSummary = {
15
+ type: string;
16
+ id: string;
17
+ hash: string | null;
18
+ reasons: string[];
19
+ debugInfo?: unknown;
20
+ };
21
+ export type NativeFingerprint = {
22
+ status: 'stable';
23
+ schemeVersion: 1;
24
+ platform: 'ios' | 'android';
25
+ runtimeVersion: string;
26
+ nativeHash: string;
27
+ manualBoundary: string | null;
28
+ sources: FingerprintSourceSummary[];
29
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1 @@
1
+ export declare function runFingerprintWorker(args: string[]): Promise<void>;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runFingerprintWorker = runFingerprintWorker;
4
+ const collect_1 = require("./collect");
5
+ async function runFingerprintWorker(args) {
6
+ const [projectRoot, platform] = args;
7
+ if (!projectRoot || (platform !== 'ios' && platform !== 'android')) {
8
+ process.stderr.write('Usage: fingerprint worker <project-root> ios|android\n');
9
+ process.exitCode = 1;
10
+ }
11
+ else {
12
+ try {
13
+ const value = await (0, collect_1.collectNativeFingerprint)(projectRoot, platform);
14
+ process.stdout.write(`${JSON.stringify(value)}\n`);
15
+ }
16
+ catch (error) {
17
+ process.stderr.write(`${error.message}\n`);
18
+ process.exitCode = 1;
19
+ }
20
+ }
21
+ }
22
+ /* istanbul ignore next -- entry point is exercised by packaged binary experiments */
23
+ if (require.main === module)
24
+ void runFingerprintWorker(process.argv.slice(2));
@@ -0,0 +1,2 @@
1
+ export declare const MAX_REPORTED_INSTALL_HASHES = 50;
2
+ export declare function mergeInstalledReportHistory(installId: string, legacyHashes: string[], reportedHash?: string): Promise<string[]>;
@@ -0,0 +1,55 @@
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.MAX_REPORTED_INSTALL_HASHES = void 0;
7
+ exports.mergeInstalledReportHistory = mergeInstalledReportHistory;
8
+ const fs_1 = __importDefault(require("../native/fs"));
9
+ const context_1 = require("../context");
10
+ const fsUtils_1 = require("./fsUtils");
11
+ exports.MAX_REPORTED_INSTALL_HASHES = 50;
12
+ // Serialize read/merge/write so simultaneous reports for different hashes cannot
13
+ // overwrite one another. This file outlives disposable current-bundle metadata.
14
+ let pendingWrite = Promise.resolve();
15
+ function mergeInstalledReportHistory(installId, legacyHashes, reportedHash) {
16
+ const path = `${context_1.BUNDLE_DROP_ROOT}/installed-report-history.json`;
17
+ const scope = JSON.stringify([context_1.config.serverUrl, context_1.config.org.slug, context_1.config.project.slug, installId]);
18
+ const operation = pendingWrite.then(async () => {
19
+ let existing;
20
+ if (await fs_1.default.exists(path)) {
21
+ const contents = await fs_1.default.readFile(path, 'utf8');
22
+ try {
23
+ existing = JSON.parse(contents);
24
+ }
25
+ catch {
26
+ existing = null;
27
+ }
28
+ if (typeof existing?.scope !== 'string' || !Array.isArray(existing.hashes)
29
+ || existing.hashes.some(hash => typeof hash !== 'string')) {
30
+ existing = null;
31
+ }
32
+ }
33
+ // Legacy metadata has no scope. Migrate it only when creating the ledger,
34
+ // never after a known installation/project change.
35
+ const sameScope = existing?.scope === scope;
36
+ const hashes = [...new Set([
37
+ ...(sameScope ? existing.hashes : []),
38
+ ...(existing === undefined ? legacyHashes : []),
39
+ ])];
40
+ if (reportedHash) {
41
+ const previous = hashes.indexOf(reportedHash);
42
+ if (previous !== -1)
43
+ hashes.splice(previous, 1);
44
+ hashes.push(reportedHash);
45
+ }
46
+ const bounded = hashes.slice(-exports.MAX_REPORTED_INSTALL_HASHES);
47
+ if (!sameScope || JSON.stringify(existing.hashes) !== JSON.stringify(bounded)) {
48
+ await (0, fsUtils_1.ensureDir)(context_1.BUNDLE_DROP_ROOT);
49
+ await fs_1.default.writeFile(path, JSON.stringify({ scope, hashes: bounded }), 'utf8');
50
+ }
51
+ return bounded;
52
+ });
53
+ pendingWrite = operation.catch(() => { });
54
+ return operation;
55
+ }
@@ -1,3 +1,4 @@
1
+ import type { FingerprintOptions } from './fingerprint/types';
1
2
  /**
2
3
  * Shape of `bundle.drop.config.js` after it is loaded through Metro.
3
4
  */
@@ -39,13 +40,16 @@ export type BundleDropProjectConfig = {
39
40
  * declaration with the concrete values embedded in the build.
40
41
  */
41
42
  runtimeVersion?: {
43
+ /** Missing selector preserves manual runtimes. Fingerprinting is experimental. */
44
+ compatibilitySource?: 'manual' | 'fingerprint';
45
+ fingerprint?: FingerprintOptions;
42
46
  /** iOS runtime version. */
43
47
  ios?: string | {
44
- source: 'appVersion' | 'nativeVersion';
48
+ source: 'appVersion' | 'nativeVersion' | 'native';
45
49
  };
46
50
  /** Android runtime version. */
47
51
  android?: string | {
48
- source: 'appVersion' | 'nativeVersion';
52
+ source: 'appVersion' | 'nativeVersion' | 'native';
49
53
  };
50
54
  } | {
51
55
  /** Explicitly resolve concrete values from the evaluated Expo app config. */
@@ -15,6 +15,7 @@ export type DownloadUpdateResult = {
15
15
  } | {
16
16
  status: 'rollback';
17
17
  reason?: string;
18
+ pendingApply?: boolean;
18
19
  };
19
20
  type DownloadOptions = {
20
21
  channelName?: string;
@@ -145,6 +145,10 @@ async function downloadAndStageUpdate(options, onStatusUpdate) {
145
145
  projectSlug: project.slug,
146
146
  platform,
147
147
  runtimeVersionValue: serverRuntimeVersion,
148
+ // The resolve decision supplies this target's full ZIP. Managed
149
+ // capability rejection must instead retain its bounded refresh path.
150
+ allowUnmanagedPatchAuthFallback: !unresolvedCheckResult.runtimeDelivery &&
151
+ !checkResult.runtimeDelivery && checkResult.fallback?.mode === 'full',
148
152
  statusCb,
149
153
  });
150
154
  if (!installResult) {
@@ -0,0 +1,11 @@
1
+ export type PendingRollback = {
2
+ schemaVersion: 1;
3
+ channelName: string;
4
+ currentHash: string | null;
5
+ runtimeVersion: string | null;
6
+ reason?: string;
7
+ };
8
+ export declare function readPendingRollback(): Promise<PendingRollback | null>;
9
+ export declare function stageRollback(channelName: string, reason?: string): Promise<void>;
10
+ export declare function clearPendingRollback(): Promise<void>;
11
+ export declare function isPendingRollbackCurrent(intent: PendingRollback, channelName: string): Promise<boolean>;
@@ -0,0 +1,54 @@
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.readPendingRollback = readPendingRollback;
7
+ exports.stageRollback = stageRollback;
8
+ exports.clearPendingRollback = clearPendingRollback;
9
+ exports.isPendingRollbackCurrent = isPendingRollbackCurrent;
10
+ const context_1 = require("../context");
11
+ const bundlePointer_1 = require("../fs/bundlePointer");
12
+ const fsUtils_1 = require("../fs/fsUtils");
13
+ const fs_1 = __importDefault(require("../native/fs"));
14
+ const PENDING_ROLLBACK_PATH = `${context_1.BUNDLE_DROP_ROOT}/pending-rollback.json`;
15
+ async function readPendingRollback() {
16
+ try {
17
+ if (!await fs_1.default.exists(PENDING_ROLLBACK_PATH))
18
+ return null;
19
+ const value = JSON.parse(await fs_1.default.readFile(PENDING_ROLLBACK_PATH, 'utf8'));
20
+ if (value?.schemaVersion !== 1 ||
21
+ typeof value.channelName !== 'string' ||
22
+ !(value.currentHash === null ||
23
+ (typeof value.currentHash === 'string' && /^[a-f0-9]{64}$/.test(value.currentHash))) ||
24
+ !(value.runtimeVersion === null || typeof value.runtimeVersion === 'string') ||
25
+ !(value.reason === undefined || typeof value.reason === 'string')) {
26
+ throw new Error('Invalid pending BundleDrop rollback');
27
+ }
28
+ return value;
29
+ }
30
+ catch (error) {
31
+ console.warn('⚠️ Ignoring unreadable BundleDrop pending rollback:', error);
32
+ return null;
33
+ }
34
+ }
35
+ async function stageRollback(channelName, reason) {
36
+ const intent = {
37
+ schemaVersion: 1,
38
+ channelName,
39
+ currentHash: await (0, bundlePointer_1.readCurrentBundleHash)(),
40
+ runtimeVersion: context_1.runtimeVersion ?? null,
41
+ reason,
42
+ };
43
+ await (0, fsUtils_1.ensureDir)(context_1.BUNDLE_DROP_ROOT);
44
+ await (0, fsUtils_1.atomicWriteJson)(PENDING_ROLLBACK_PATH, intent);
45
+ }
46
+ async function clearPendingRollback() {
47
+ if (await fs_1.default.exists(PENDING_ROLLBACK_PATH))
48
+ await fs_1.default.unlink(PENDING_ROLLBACK_PATH);
49
+ }
50
+ async function isPendingRollbackCurrent(intent, channelName) {
51
+ return intent.channelName === channelName &&
52
+ intent.runtimeVersion === (context_1.runtimeVersion ?? null) &&
53
+ intent.currentHash === await (0, bundlePointer_1.readCurrentBundleHash)();
54
+ }
@@ -7,6 +7,7 @@ export type FailedBundleRecord = {
7
7
  runtimeVersion?: string;
8
8
  previousHash?: string;
9
9
  };
10
+ export declare function preserveInstalledReportHistory(info: BundleInfo): Promise<void>;
10
11
  export declare function reportInstalledIfReady(state?: {
11
12
  hasBundle?: boolean;
12
13
  info?: BundleInfo | null;
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.preserveInstalledReportHistory = preserveInstalledReportHistory;
3
4
  exports.reportInstalledIfReady = reportInstalledIfReady;
4
5
  exports.reportLocalRollback = reportLocalRollback;
5
6
  const context_1 = require("../context");
@@ -9,11 +10,27 @@ const bundleDropNative_1 = require("../native/bundleDropNative");
9
10
  const installId_1 = require("../fs/installId");
10
11
  const userProperties_1 = require("../fs/userProperties");
11
12
  const initState_1 = require("../runtime/initState");
12
- const MAX_REPORTED_INSTALL_HASHES = 50;
13
+ const installedReportHistory_1 = require("../fs/installedReportHistory");
13
14
  const installedReportInFlightHashes = new Set();
14
15
  function appendReportedHash(existing, hash) {
15
16
  const next = [...(existing || []).filter(value => value !== hash), hash];
16
- return next.slice(-MAX_REPORTED_INSTALL_HASHES);
17
+ return next.slice(-installedReportHistory_1.MAX_REPORTED_INSTALL_HASHES);
18
+ }
19
+ function legacyReportedHashes(info) {
20
+ return [
21
+ ...(info.installedReportedHashes ?? []),
22
+ ...(info.lastInstalledReportedHash ? [info.lastInstalledReportedHash] : []),
23
+ ];
24
+ }
25
+ async function preserveInstalledReportHistory(info) {
26
+ try {
27
+ const installId = await (0, installId_1.getOrCreateInstallId)();
28
+ await (0, installedReportHistory_1.mergeInstalledReportHistory)(installId, legacyReportedHashes(info));
29
+ }
30
+ catch (e) {
31
+ // Reporting persistence must not prevent authoritative embedded recovery.
32
+ console.warn('⚠️ Failed to preserve install-report history:', e);
33
+ }
17
34
  }
18
35
  async function getReportingState() {
19
36
  const info = await (0, bundleInfo_1.readBundleInfo)();
@@ -33,10 +50,6 @@ async function reportInstalledIfReady(state) {
33
50
  return;
34
51
  if (hasBundle === false)
35
52
  return;
36
- if (info.lastInstalledReportedHash === info.hash)
37
- return;
38
- if (info.installedReportedHashes?.includes(info.hash))
39
- return;
40
53
  if (installedReportInFlightHashes.has(info.hash))
41
54
  return;
42
55
  const reportedHash = info.hash;
@@ -46,6 +59,9 @@ async function reportInstalledIfReady(state) {
46
59
  (0, installId_1.getOrCreateInstallId)(),
47
60
  (0, userProperties_1.getCurrentUserProperties)(),
48
61
  ]);
62
+ const history = await (0, installedReportHistory_1.mergeInstalledReportHistory)(installId, legacyReportedHashes(info));
63
+ if (history.includes(reportedHash))
64
+ return;
49
65
  const appEnvironment = (0, initState_1.getBundleDropRuntimeConfig)()?.environment ?? null;
50
66
  await (0, clientApi_1.reportInstalled)(context_1.config.project.slug, reportedHash, {
51
67
  channelName: info.channelName,
@@ -55,6 +71,7 @@ async function reportInstalledIfReady(state) {
55
71
  environment: appEnvironment,
56
72
  userProperties: Object.keys(userProperties).length > 0 ? userProperties : undefined,
57
73
  });
74
+ await (0, installedReportHistory_1.mergeInstalledReportHistory)(installId, [], reportedHash);
58
75
  const latestInfo = await (0, bundleInfo_1.readBundleInfo)();
59
76
  if (latestInfo) {
60
77
  const nextInfo = {
@@ -7,6 +7,9 @@ export type ApplyUpdateResult = {
7
7
  status: 'disabled';
8
8
  } | {
9
9
  status: 'alreadyApplied';
10
+ } | {
11
+ status: 'blocked';
12
+ reason: 'ROLLBACK_REVALIDATION_FAILED';
10
13
  } | {
11
14
  status: 'blocked';
12
15
  reason: 'BUNDLE_PREVIOUSLY_FAILED';
@@ -57,6 +57,7 @@ const reconcileAppliedBundleOnLaunch = async (cached) => {
57
57
  const state = await (0, exports.getUpdateState)({ ...cached, bundlePath });
58
58
  if (!state.hasBundle) {
59
59
  if (state.info) {
60
+ await (0, reporting_1.preserveInstalledReportHistory)(state.info);
60
61
  await (0, bundleInfo_1.deleteBundleInfo)();
61
62
  }
62
63
  return null;