@gfean/react-native-bundle-drop 0.6.0 → 0.7.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 (58) hide show
  1. package/BundleDrop.podspec +96 -0
  2. package/README.md +34 -9
  3. package/android/build.gradle +65 -0
  4. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +137 -13
  5. package/android/src/main/java/com/bundledrop/BundleDropNativePaths.kt +43 -13
  6. package/android/src/main/java/com/bundledrop/BundleDropOtaResolver.kt +35 -0
  7. package/android/src/main/java/com/bundledrop/BundleDropStartupRecovery.kt +1117 -0
  8. package/ios/BundleDropBridge.m +27 -0
  9. package/ios/BundleDropLocator.swift +31 -15
  10. package/ios/BundleDropModule.swift +106 -3
  11. package/ios/BundleDropOtaResolver.swift +137 -29
  12. package/ios/BundleDropStartupRecovery.swift +1108 -0
  13. package/ios/BundleDropStartupRecoveryAdapter.swift +301 -0
  14. package/lib/CLI/cli.js +4 -5
  15. package/lib/CLI/scripts/doctor.js +28 -9
  16. package/lib/CLI/scripts/expo/configure-expo.js +2 -1
  17. package/lib/CLI/scripts/init-config.d.ts +2 -2
  18. package/lib/CLI/scripts/init-config.js +23 -14
  19. package/lib/CLI/scripts/login-cli.js +2 -3
  20. package/lib/CLI/scripts/native/write-runtime-identity.d.ts +19 -0
  21. package/lib/CLI/scripts/native/write-runtime-identity.js +92 -0
  22. package/lib/CLI/scripts/upload-cli.d.ts +12 -2
  23. package/lib/CLI/scripts/upload-cli.js +74 -11
  24. package/lib/CLI/serverUrl.d.ts +3 -0
  25. package/lib/CLI/serverUrl.js +31 -0
  26. package/lib/bundleInfo.d.ts +2 -0
  27. package/lib/bundleInfo.js +16 -1
  28. package/lib/context.js +12 -2
  29. package/lib/fs/bundlePointer.d.ts +1 -17
  30. package/lib/fs/bundlePointer.js +5 -93
  31. package/lib/install/bundleInstallShared.js +4 -4
  32. package/lib/manager/downloadAndInstall.js +25 -22
  33. package/lib/manager/reporting.d.ts +8 -1
  34. package/lib/manager/reporting.js +17 -22
  35. package/lib/manager/rollbackState.d.ts +18 -54
  36. package/lib/manager/rollbackState.js +115 -216
  37. package/lib/manager/updateCheck.js +9 -3
  38. package/lib/manager/updateState.d.ts +2 -1
  39. package/lib/manager/updateState.js +59 -6
  40. package/lib/metro.d.ts +1 -1
  41. package/lib/metro.js +4 -3
  42. package/lib/native/bundleDropNative.d.ts +62 -0
  43. package/lib/native/bundleDropNative.js +266 -1
  44. package/lib/patch-engine/installFromPatchSet.js +2 -2
  45. package/lib/runtime/service.js +29 -71
  46. package/lib/runtime-delivery/bootstrapConfig.d.ts +29 -11
  47. package/lib/runtime-delivery/bootstrapConfig.js +83 -22
  48. package/lib/runtime-delivery/manifestState.d.ts +3 -1
  49. package/lib/runtime-delivery/manifestState.js +22 -1
  50. package/lib/runtime-delivery/manifestVerifier.js +7 -1
  51. package/lib/scripts/bundle.d.ts +9 -2
  52. package/lib/scripts/bundle.js +68 -18
  53. package/lib/scripts/download-bundle.d.ts +1 -0
  54. package/lib/scripts/download-bundle.js +2 -2
  55. package/lib/scripts/resolveModule.d.ts +2 -0
  56. package/lib/scripts/resolveModule.js +5 -0
  57. package/package.json +5 -2
  58. package/plugin/xcodeBuildPhase.js +2 -1
@@ -74,26 +74,21 @@ async function reportInstalledIfReady(state) {
74
74
  }
75
75
  }
76
76
  async function reportLocalRollback(hash, record) {
77
- try {
78
- const [installId, userProperties] = await Promise.all([
79
- (0, installId_1.getOrCreateInstallId)(),
80
- (0, userProperties_1.getCurrentUserProperties)(),
81
- ]);
82
- const appEnvironment = (0, initState_1.getBundleDropRuntimeConfig)()?.environment ?? null;
83
- await (0, clientApi_1.reportLocalRollback)(context_1.config.project.slug, hash, {
84
- reason: record.reason,
85
- previousHash: record.previousHash ?? null,
86
- channelName: record.channelName ?? null,
87
- platform: context_1.platform,
88
- installId,
89
- runtimeVersion: record.runtimeVersion ?? context_1.runtimeVersion ?? null,
90
- environment: appEnvironment,
91
- userProperties: Object.keys(userProperties).length > 0 ? userProperties : undefined,
92
- crashCount: record.crashCount ?? null,
93
- failedAt: record.failedAt ? new Date(record.failedAt * 1000).toISOString() : null,
94
- });
95
- }
96
- catch (e) {
97
- console.warn('⚠️ Failed to report local rollback:', e?.toString?.() || e);
98
- }
77
+ const [installId, userProperties] = await Promise.all([
78
+ (0, installId_1.getOrCreateInstallId)(),
79
+ (0, userProperties_1.getCurrentUserProperties)(),
80
+ ]);
81
+ const appEnvironment = (0, initState_1.getBundleDropRuntimeConfig)()?.environment ?? null;
82
+ await (0, clientApi_1.reportLocalRollback)(context_1.config.project.slug, hash, {
83
+ reason: record.reason,
84
+ previousHash: record.previousHash ?? null,
85
+ channelName: record.channelName ?? null,
86
+ platform: context_1.platform,
87
+ installId,
88
+ runtimeVersion: record.runtimeVersion ?? context_1.runtimeVersion ?? null,
89
+ environment: appEnvironment,
90
+ userProperties: Object.keys(userProperties).length > 0 ? userProperties : undefined,
91
+ crashCount: record.crashCount ?? null,
92
+ failedAt: record.failedAt ? new Date(record.failedAt * 1000).toISOString() : null,
93
+ });
99
94
  }
@@ -1,60 +1,24 @@
1
- import { type BundlePointer } from '../fs/bundlePointer';
1
+ import type { BundleInfo } from '../bundleInfo';
2
+ import { type StartupRecoveryState, type StartupCandidateActivation, type StartupRollbackResult } from '../native/bundleDropNative';
2
3
  export type RollbackPolicy = {
3
4
  maxCrashCount?: number;
4
5
  healthCheckMode?: 'auto' | 'manual';
5
6
  healthyAfterSec?: number;
6
7
  };
7
- export type FailedBundleReason = 'crash_loop';
8
- export type FailedBundleRecord = {
9
- reason: FailedBundleReason;
10
- failedAt: number;
11
- crashCount?: number;
12
- channelName?: string;
13
- runtimeVersion?: string;
14
- previousHash?: string;
15
- };
16
- export type RollbackState = {
17
- activeHash?: string;
18
- lastGoodHash?: string;
19
- candidateHash?: string;
20
- candidateActivatedAt?: number;
21
- candidateCommitted?: boolean;
22
- crashCount?: number;
23
- lastLaunchAt?: number;
24
- failedBundles?: Record<string, FailedBundleRecord>;
25
- };
26
- type RollbackDecision = {
27
- shouldRollback: false;
28
- } | {
29
- shouldRollback: true;
30
- reason: FailedBundleReason;
31
- };
32
- declare function readState(): Promise<RollbackState | null>;
33
- export { readState as readRollbackState };
34
- export declare function markCandidateActivated(hash: string): Promise<void>;
35
- export declare function reportActiveBundleHealthy(cached?: {
36
- currentPointer?: BundlePointer | null;
37
- }, expectedHash?: string): Promise<boolean>;
38
- export declare function commitActiveBundle(cached?: {
39
- currentPointer?: BundlePointer | null;
40
- }): Promise<void>;
41
- export declare function isBundleHashFailed(hash?: string | null): Promise<boolean>;
42
- export declare function getFailedBundleHashes(): Promise<string[]>;
43
- export declare function evaluateRollbackOnLaunch(policy: Required<RollbackPolicy>, cached?: {
44
- currentPointer?: BundlePointer | null;
45
- rollbackState?: RollbackState | null;
46
- }): Promise<RollbackDecision>;
47
- export declare function rollbackToPreviousIfNeeded(policy: Required<RollbackPolicy>, cached?: {
48
- currentPointer?: BundlePointer | null;
49
- rollbackState?: RollbackState | null;
50
- }): Promise<{
51
- rolledBack: boolean;
52
- reason?: FailedBundleReason;
53
- }>;
8
+ export type { FailedBundleRecord } from './reporting';
9
+ export type { StartupRecoveryState } from '../native/bundleDropNative';
10
+ export declare const STARTUP_RECOVERY_TELEMETRY_CONTEXT_PATH: string;
54
11
  export declare function getRollbackPolicy(): Required<RollbackPolicy>;
55
- export declare function rollbackToPreviousOrNative(options?: {
56
- forceNative?: boolean;
57
- }): Promise<{
58
- rolledBack: boolean;
59
- toNative?: boolean;
60
- }>;
12
+ export declare function activateStartupCandidate(hash: string): Promise<StartupCandidateActivation | null>;
13
+ export declare function reportActiveBundleHealthy(): Promise<boolean>;
14
+ export declare function readStartupRecoveryState(): Promise<StartupRecoveryState | null>;
15
+ export declare function getFailedBundleHashes(cachedState?: StartupRecoveryState | null): Promise<string[]>;
16
+ export declare function isBundleHashFailed(hash?: string | null): Promise<boolean>;
17
+ export declare function syncVerifiedRevokedHashes(hashes: string[]): Promise<boolean>;
18
+ export declare function rollbackStartupBundle(forceEmbedded: boolean): Promise<StartupRollbackResult | null>;
19
+ /**
20
+ * Flush native recovery events without making JS part of the recovery decision.
21
+ * Native keeps each event durable until its backend report succeeds and JS
22
+ * acknowledges that exact event id.
23
+ */
24
+ export declare function reconcileStartupRecovery(cachedState?: StartupRecoveryState | null, failedBundleInfo?: BundleInfo | null): Promise<StartupRecoveryState | null>;
@@ -3,246 +3,145 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.readRollbackState = readState;
7
- exports.markCandidateActivated = markCandidateActivated;
6
+ exports.STARTUP_RECOVERY_TELEMETRY_CONTEXT_PATH = void 0;
7
+ exports.getRollbackPolicy = getRollbackPolicy;
8
+ exports.activateStartupCandidate = activateStartupCandidate;
8
9
  exports.reportActiveBundleHealthy = reportActiveBundleHealthy;
9
- exports.commitActiveBundle = commitActiveBundle;
10
- exports.isBundleHashFailed = isBundleHashFailed;
10
+ exports.readStartupRecoveryState = readStartupRecoveryState;
11
11
  exports.getFailedBundleHashes = getFailedBundleHashes;
12
- exports.evaluateRollbackOnLaunch = evaluateRollbackOnLaunch;
13
- exports.rollbackToPreviousIfNeeded = rollbackToPreviousIfNeeded;
14
- exports.getRollbackPolicy = getRollbackPolicy;
15
- exports.rollbackToPreviousOrNative = rollbackToPreviousOrNative;
16
- const fs_1 = __importDefault(require("../native/fs"));
12
+ exports.isBundleHashFailed = isBundleHashFailed;
13
+ exports.syncVerifiedRevokedHashes = syncVerifiedRevokedHashes;
14
+ exports.rollbackStartupBundle = rollbackStartupBundle;
15
+ exports.reconcileStartupRecovery = reconcileStartupRecovery;
17
16
  const context_1 = require("../context");
18
17
  const fsUtils_1 = require("../fs/fsUtils");
19
- const bundlePointer_1 = require("../fs/bundlePointer");
20
- const bundleInfo_1 = require("../bundleInfo");
18
+ const fs_1 = __importDefault(require("../native/fs"));
19
+ const bundleDropNative_1 = require("../native/bundleDropNative");
21
20
  const reporting_1 = require("./reporting");
22
- const bundleManifest_1 = require("../manifest/bundleManifest");
23
- const STATE_PATH = `${context_1.BUNDLE_DROP_ROOT}/state.json`;
24
- const MAX_FAILED_BUNDLES = 20;
25
- function nowSec() {
26
- return Math.floor(Date.now() / 1000);
27
- }
28
- async function readState() {
21
+ exports.STARTUP_RECOVERY_TELEMETRY_CONTEXT_PATH = `${context_1.BUNDLE_DROP_ROOT}/recovery-telemetry-context.json`;
22
+ let telemetryContextMutation = Promise.resolve();
23
+ async function readRecoveryTelemetryContexts() {
29
24
  try {
30
- if (!(await fs_1.default.exists(STATE_PATH)))
31
- return null;
32
- const raw = await fs_1.default.readFile(STATE_PATH, 'utf8');
33
- return JSON.parse(raw);
25
+ if (!await fs_1.default.exists(exports.STARTUP_RECOVERY_TELEMETRY_CONTEXT_PATH)) {
26
+ return { schemaVersion: 1, events: {} };
27
+ }
28
+ const parsed = JSON.parse(await fs_1.default.readFile(exports.STARTUP_RECOVERY_TELEMETRY_CONTEXT_PATH, 'utf8'));
29
+ if (parsed?.schemaVersion !== 1 || !parsed.events || typeof parsed.events !== 'object') {
30
+ throw new Error('unsupported recovery telemetry context');
31
+ }
32
+ return parsed;
34
33
  }
35
- catch {
36
- return null;
34
+ catch (error) {
35
+ console.warn('⚠️ Ignoring malformed BundleDrop recovery telemetry context:', error);
36
+ return { schemaVersion: 1, events: {} };
37
37
  }
38
38
  }
39
- async function writeState(state) {
40
- await (0, fsUtils_1.ensureDir)(context_1.BUNDLE_DROP_ROOT);
41
- await (0, fsUtils_1.atomicWriteJson)(STATE_PATH, state);
39
+ async function mutateRecoveryTelemetryContexts(mutate) {
40
+ let result = { schemaVersion: 1, events: {} };
41
+ const mutation = telemetryContextMutation.then(async () => {
42
+ result = await readRecoveryTelemetryContexts();
43
+ if (!mutate(result))
44
+ return;
45
+ await (0, fsUtils_1.ensureDir)(context_1.BUNDLE_DROP_ROOT);
46
+ await (0, fsUtils_1.atomicWriteJson)(exports.STARTUP_RECOVERY_TELEMETRY_CONTEXT_PATH, result);
47
+ });
48
+ telemetryContextMutation = mutation.then(() => undefined, () => undefined);
49
+ await mutation;
50
+ return result;
51
+ }
52
+ async function prepareRecoveryTelemetryContexts(events, failedBundleInfo) {
53
+ const pendingEventIds = new Set(events.map(event => event.id));
54
+ return mutateRecoveryTelemetryContexts(state => {
55
+ let changed = false;
56
+ for (const eventId of Object.keys(state.events)) {
57
+ if (!pendingEventIds.has(eventId)) {
58
+ delete state.events[eventId];
59
+ changed = true;
60
+ }
61
+ }
62
+ for (const event of events) {
63
+ if (!state.events[event.id] &&
64
+ failedBundleInfo?.hash === event.failedHash) {
65
+ state.events[event.id] = {
66
+ failedHash: event.failedHash,
67
+ channelName: failedBundleInfo.channelName,
68
+ runtimeVersion: failedBundleInfo.runtimeVersion,
69
+ };
70
+ changed = true;
71
+ }
72
+ }
73
+ return changed;
74
+ });
42
75
  }
43
- async function updateState(partial) {
44
- const existing = (await readState()) || {};
45
- const next = { ...existing, ...partial };
46
- await writeState(next);
47
- return next;
76
+ async function removeRecoveryTelemetryContext(eventId) {
77
+ await mutateRecoveryTelemetryContexts(state => {
78
+ if (!state.events[eventId])
79
+ return false;
80
+ delete state.events[eventId];
81
+ return true;
82
+ });
48
83
  }
49
- function pruneFailedBundles(failedBundles) {
50
- return Object.fromEntries(Object.entries(failedBundles)
51
- .sort(([, left], [, right]) => right.failedAt - left.failedAt)
52
- .slice(0, MAX_FAILED_BUNDLES));
84
+ function getRollbackPolicy() {
85
+ return context_1.bundleDropConfig.rollback;
53
86
  }
54
- async function markCandidateActivated(hash) {
55
- const previous = await (0, bundlePointer_1.readPreviousBundlePointer)();
56
- const previousHash = previous?.hash;
57
- const now = nowSec();
58
- await updateState({
59
- activeHash: hash,
60
- candidateHash: hash,
61
- candidateActivatedAt: now,
62
- candidateCommitted: false,
63
- crashCount: 0,
64
- lastLaunchAt: now,
65
- lastGoodHash: previousHash ?? undefined,
66
- });
87
+ async function activateStartupCandidate(hash) {
88
+ return (0, bundleDropNative_1.activateStartupCandidateNative)(hash, getRollbackPolicy());
67
89
  }
68
- async function reportActiveBundleHealthy(cached, expectedHash) {
69
- const current = cached?.currentPointer !== undefined ? cached.currentPointer : await (0, bundlePointer_1.readCurrentBundlePointer)();
70
- const hash = current?.hash;
71
- if (!hash)
72
- return false;
73
- if (expectedHash && hash !== expectedHash)
74
- return false;
75
- const state = (await readState()) || {};
76
- const isCandidate = state.candidateHash === hash && state.candidateCommitted !== true;
77
- if (!isCandidate)
90
+ async function reportActiveBundleHealthy() {
91
+ const attempt = (0, bundleDropNative_1.getStartupRecoveryAttemptNative)();
92
+ if (!attempt)
78
93
  return false;
79
- await updateState({
80
- activeHash: hash,
81
- candidateHash: hash,
82
- candidateCommitted: true,
83
- crashCount: 0,
84
- lastGoodHash: hash,
85
- });
86
- return true;
94
+ return (0, bundleDropNative_1.markStartupHealthyNative)(attempt);
95
+ }
96
+ async function readStartupRecoveryState() {
97
+ return (0, bundleDropNative_1.getStartupRecoveryStateNative)();
87
98
  }
88
- async function commitActiveBundle(cached) {
89
- await reportActiveBundleHealthy(cached);
99
+ async function getFailedBundleHashes(cachedState) {
100
+ const state = cachedState === undefined ? await readStartupRecoveryState() : cachedState;
101
+ return [...(state?.quarantinedHashes || [])];
90
102
  }
91
103
  async function isBundleHashFailed(hash) {
92
104
  if (!hash)
93
105
  return false;
94
- const state = await readState();
95
- return !!state?.failedBundles?.[hash];
106
+ return (await getFailedBundleHashes()).includes(hash);
96
107
  }
97
- async function getFailedBundleHashes() {
98
- const state = await readState();
99
- return Object.entries(state?.failedBundles || {})
100
- .sort(([, left], [, right]) => right.failedAt - left.failedAt)
101
- .slice(0, MAX_FAILED_BUNDLES)
102
- .map(([hash]) => hash);
108
+ async function syncVerifiedRevokedHashes(hashes) {
109
+ return (0, bundleDropNative_1.setStartupRecoveryRevokedHashesNative)(hashes);
103
110
  }
104
- async function buildFailedBundleRecord(hash, reason, state) {
105
- const [bundleInfo, previous] = await Promise.all([
106
- (0, bundleInfo_1.readBundleInfo)(),
107
- (0, bundlePointer_1.readPreviousBundlePointer)(),
108
- ]);
109
- const record = {
110
- reason,
111
- failedAt: nowSec(),
112
- crashCount: state.crashCount,
113
- channelName: bundleInfo?.channelName,
114
- runtimeVersion: bundleInfo?.runtimeVersion,
115
- previousHash: previous?.hash,
116
- };
117
- return record;
111
+ async function rollbackStartupBundle(forceEmbedded) {
112
+ return (0, bundleDropNative_1.rollbackStartupBundleNative)(forceEmbedded);
118
113
  }
119
- async function recordFailedBundle(hash, record) {
120
- const state = (await readState()) || {};
121
- const failedBundles = pruneFailedBundles({
122
- ...(state.failedBundles || {}),
123
- [hash]: record,
124
- });
125
- await updateState({ failedBundles });
126
- }
127
- async function evaluateRollbackOnLaunch(policy, cached) {
128
- const current = cached?.currentPointer !== undefined ? cached.currentPointer : await (0, bundlePointer_1.readCurrentBundlePointer)();
129
- const activeHash = current?.hash;
130
- if (!activeHash)
131
- return { shouldRollback: false };
132
- const now = nowSec();
133
- const persistedState = (await readState()) || {};
134
- const state = cached?.rollbackState !== undefined
135
- ? {
136
- ...persistedState,
137
- ...cached.rollbackState,
138
- failedBundles: persistedState.failedBundles ?? cached.rollbackState?.failedBundles,
139
- }
140
- : persistedState;
141
- const next = {
142
- ...state,
143
- activeHash,
144
- lastLaunchAt: now,
114
+ function recoveryRecord(event, context) {
115
+ return {
116
+ reason: event.reason,
117
+ failedAt: event.failedAt,
118
+ crashCount: event.crashCount,
119
+ channelName: context?.channelName,
120
+ runtimeVersion: context?.runtimeVersion,
121
+ previousHash: event.recoveredHash,
145
122
  };
146
- const isCandidate = state.candidateHash === activeHash && state.candidateCommitted !== true;
147
- if (isCandidate) {
148
- const crashCount = (state.crashCount ?? 0) + 1;
149
- next.crashCount = crashCount;
150
- if (policy.maxCrashCount > 0 &&
151
- crashCount >= policy.maxCrashCount) {
152
- await writeState(next);
153
- return { shouldRollback: true, reason: 'crash_loop' };
154
- }
155
- }
156
- await writeState(next);
157
- return { shouldRollback: false };
158
123
  }
159
- async function rollbackToPreviousIfNeeded(policy, cached) {
160
- const decision = await evaluateRollbackOnLaunch(policy, cached);
161
- if (!decision.shouldRollback)
162
- return { rolledBack: false };
163
- const current = cached?.currentPointer !== undefined ? cached.currentPointer : await (0, bundlePointer_1.readCurrentBundlePointer)();
164
- const failedHash = current?.hash;
165
- const state = (await readState()) || {};
166
- if (!failedHash)
167
- return { rolledBack: false };
168
- const failedRecord = await buildFailedBundleRecord(failedHash, decision.reason, state);
169
- await rollbackToPreviousOrNative();
170
- await recordFailedBundle(failedHash, failedRecord);
171
- await (0, reporting_1.reportLocalRollback)(failedHash, failedRecord).catch(() => undefined);
172
- return { rolledBack: true, reason: decision.reason };
173
- }
174
- function getRollbackPolicy() {
175
- return context_1.bundleDropConfig.rollback;
176
- }
177
- async function rollbackToPreviousOrNative(options = {}) {
178
- const [current, previous, state] = await Promise.all([
179
- (0, bundlePointer_1.readCurrentBundlePointer)(),
180
- (0, bundlePointer_1.readPreviousBundlePointer)(),
181
- readState(),
182
- ]);
183
- const previousIsFailed = previous ? !!state?.failedBundles?.[previous.hash] : false;
184
- if (!options.forceNative && previous && previous.hash !== current?.hash && !previousIsFailed) {
185
- await (0, bundlePointer_1.writeCurrentBundlePointer)({ ...previous, updatedAt: new Date().toISOString() });
186
- const metadata = await readBundleMetadata(previous.bundlePath);
187
- await (0, bundleInfo_1.updateBundleInfo)({
188
- hash: previous.hash,
189
- bundleVersion: metadata?.bundleVersion,
190
- version: metadata?.version,
191
- runtimeVersion: metadata?.runtimeVersion,
192
- pendingApply: false,
193
- installedAt: new Date().toISOString(),
194
- lastInstalledReportedHash: previous.hash,
195
- });
196
- await updateState({
197
- activeHash: previous.hash,
198
- candidateHash: previous.hash,
199
- candidateCommitted: true,
200
- crashCount: 0,
201
- lastGoodHash: previous.hash,
202
- });
203
- return { rolledBack: true };
204
- }
205
- // No previous OTA bundle exists; fall back to native bundle by clearing the active pointer.
206
- await (0, bundlePointer_1.deleteCurrentBundlePointer)();
207
- await (0, bundlePointer_1.deletePreviousBundlePointer)();
208
- await (0, bundleInfo_1.updateBundleInfo)({
209
- hash: undefined,
210
- bundleVersion: undefined,
211
- version: undefined,
212
- runtimeVersion: undefined,
213
- pendingApply: false,
214
- installedAt: new Date().toISOString(),
215
- });
216
- await updateState({
217
- activeHash: undefined,
218
- candidateHash: undefined,
219
- candidateCommitted: true,
220
- crashCount: 0,
221
- });
222
- return { rolledBack: true, toNative: true };
223
- }
224
- async function readJsonIfExists(path) {
225
- try {
226
- if (!(await fs_1.default.exists(path)))
227
- return null;
228
- const raw = await fs_1.default.readFile(path, 'utf8');
229
- return JSON.parse(raw);
230
- }
231
- catch {
232
- return null;
233
- }
234
- }
235
- async function readBundleMetadata(bundlePath) {
236
- const dir = bundlePath.substring(0, bundlePath.lastIndexOf('/'));
237
- const manifest = await readJsonIfExists(`${dir}/${bundleManifest_1.BUNDLE_MANIFEST}`);
238
- const metadataFile = context_1.platform === 'android' ? 'metadata-android.json' : 'metadata-ios.json';
239
- const parsed = await readJsonIfExists(`${dir}/${metadataFile}`);
240
- if (!manifest && !parsed) {
124
+ /**
125
+ * Flush native recovery events without making JS part of the recovery decision.
126
+ * Native keeps each event durable until its backend report succeeds and JS
127
+ * acknowledges that exact event id.
128
+ */
129
+ async function reconcileStartupRecovery(cachedState, failedBundleInfo) {
130
+ const state = cachedState === undefined ? await readStartupRecoveryState() : cachedState;
131
+ if (!state)
241
132
  return null;
133
+ const telemetryContexts = await prepareRecoveryTelemetryContexts(state.pendingRecoveryEvents, failedBundleInfo);
134
+ for (const event of state.pendingRecoveryEvents) {
135
+ try {
136
+ const telemetryContext = telemetryContexts.events[event.id];
137
+ await (0, reporting_1.reportLocalRollback)(event.failedHash, recoveryRecord(event, telemetryContext?.failedHash === event.failedHash ? telemetryContext : undefined));
138
+ if (await (0, bundleDropNative_1.acknowledgeStartupRecoveryNative)(event.id)) {
139
+ await removeRecoveryTelemetryContext(event.id);
140
+ }
141
+ }
142
+ catch (error) {
143
+ console.warn(`⚠️ Failed to report BundleDrop startup recovery event ${event.id}:`, error?.toString?.() || error);
144
+ }
242
145
  }
243
- return {
244
- bundleVersion: parsed?.bundleVersion,
245
- version: manifest?.version ?? parsed?.version,
246
- runtimeVersion: manifest?.runtimeVersion ?? parsed?.runtimeVersion,
247
- };
146
+ return state;
248
147
  }
@@ -106,8 +106,9 @@ async function getAvailableChannels() {
106
106
  }
107
107
  }
108
108
  async function readResolveContext(channelName) {
109
- const [currentPtr, nativeBundlePath, userProperties, installId, rejectedHashes] = await Promise.all([
110
- (0, bundlePointer_1.readCurrentBundlePointer)(),
109
+ const selectedHash = (0, bundleDropNative_1.getStartupRecoverySelectedHashNative)();
110
+ const [pointerHash, nativeBundlePath, userProperties, installId, rejectedHashes] = await Promise.all([
111
+ (0, bundlePointer_1.readCurrentBundleHash)(),
111
112
  (0, bundleDropNative_1.getDownloadedBundlePathNative)(),
112
113
  (0, userProperties_1.getCurrentUserProperties)(),
113
114
  (0, installId_1.getOrCreateInstallId)(),
@@ -117,7 +118,12 @@ async function readResolveContext(channelName) {
117
118
  .catch(() => false);
118
119
  return {
119
120
  channelName,
120
- currentHash: nativeBundlePath && currentPtr?.hash ? currentPtr.hash : null,
121
+ // Only adapters that predate startupRecoverySelectedHash infer the running
122
+ // identity from passive eligibility. New adapters distinguish embedded
123
+ // selection from an OTA that became ineligible after this runtime started.
124
+ currentHash: selectedHash === undefined
125
+ ? nativeBundlePath && pointerHash ? pointerHash : null
126
+ : selectedHash,
121
127
  rejectedHashes,
122
128
  installId,
123
129
  patchAlgorithms: (0, patchOperations_1.advertisedPatchAlgorithms)(supportsXdelta),
@@ -23,5 +23,6 @@ export declare const getUpdateState: (cached?: {
23
23
  export declare const reconcileAppliedBundleOnLaunch: (cached?: {
24
24
  bundleInfo?: BundleInfo | null;
25
25
  bundlePath?: string | null;
26
- }) => Promise<void>;
26
+ currentHash?: string | null;
27
+ }) => Promise<BundleInfo | null>;
27
28
  export declare const applyUpdate: (onStatusUpdate?: (status: string) => void, onBeforeRestart?: () => void) => Promise<ApplyUpdateResult>;
@@ -1,8 +1,14 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.applyUpdate = exports.reconcileAppliedBundleOnLaunch = exports.getUpdateState = void 0;
4
7
  const bundleDropNative_1 = require("../native/bundleDropNative");
5
8
  const bundleInfo_1 = require("../bundleInfo");
9
+ const fs_1 = __importDefault(require("../native/fs"));
10
+ const context_1 = require("../context");
11
+ const bundleVerification_1 = require("../install/bundleVerification");
6
12
  const reporting_1 = require("./reporting");
7
13
  const errors_1 = require("../errors");
8
14
  const rollbackState_1 = require("./rollbackState");
@@ -17,20 +23,67 @@ const getUpdateState = async (cached) => {
17
23
  };
18
24
  };
19
25
  exports.getUpdateState = getUpdateState;
26
+ async function readRecoveredBundleInfo(bundlePath, hash, previousInfo) {
27
+ const bundleDir = bundlePath.slice(0, bundlePath.lastIndexOf('/'));
28
+ const manifest = await (0, bundleVerification_1.verifyBundleDir)(bundleDir, hash, context_1.platform);
29
+ const metadataPath = `${bundleDir}/${context_1.platform === 'android' ? 'metadata-android.json' : 'metadata-ios.json'}`;
30
+ const metadata = await fs_1.default.exists(metadataPath)
31
+ ? await (0, bundleVerification_1.readJsonFile)(metadataPath)
32
+ : null;
33
+ const bundleVersion = typeof metadata?.bundleVersion === 'number'
34
+ ? metadata.bundleVersion
35
+ : undefined;
36
+ const metadataVersion = typeof metadata?.version === 'string' ? metadata.version : undefined;
37
+ const metadataRuntimeVersion = typeof metadata?.runtimeVersion === 'string'
38
+ ? metadata.runtimeVersion
39
+ : undefined;
40
+ const alreadyReported = previousInfo?.installedReportedHashes?.includes(hash) === true;
41
+ return {
42
+ hash,
43
+ bundleVersion,
44
+ version: manifest?.version ?? metadataVersion,
45
+ runtimeVersion: manifest?.runtimeVersion ?? metadataRuntimeVersion,
46
+ platform: context_1.platform,
47
+ installedAt: new Date().toISOString(),
48
+ pendingApply: false,
49
+ lastInstalledReportedHash: alreadyReported ? hash : undefined,
50
+ installedReportedHashes: previousInfo?.installedReportedHashes,
51
+ };
52
+ }
20
53
  const reconcileAppliedBundleOnLaunch = async (cached) => {
21
- const state = await (0, exports.getUpdateState)(cached);
22
- if (!state.hasBundle)
23
- return;
54
+ const bundlePath = cached?.bundlePath !== undefined
55
+ ? cached.bundlePath
56
+ : await (0, bundleDropNative_1.getDownloadedBundlePathNative)();
57
+ const state = await (0, exports.getUpdateState)({ ...cached, bundlePath });
58
+ if (!state.hasBundle) {
59
+ if (state.info) {
60
+ await (0, bundleInfo_1.deleteBundleInfo)();
61
+ }
62
+ return null;
63
+ }
64
+ const currentHash = cached?.currentHash;
65
+ if (currentHash && state.info?.hash !== currentHash) {
66
+ const recoveredInfo = await readRecoveredBundleInfo(bundlePath, currentHash, state.info);
67
+ await (0, bundleInfo_1.writeBundleInfoDurably)(recoveredInfo);
68
+ (0, reporting_1.reportInstalledIfReady)({ hasBundle: true, info: recoveredInfo }).catch(() => { });
69
+ return recoveredInfo;
70
+ }
24
71
  if (!state.info?.pendingApply) {
25
72
  (0, reporting_1.reportInstalledIfReady)(state).catch(() => { });
26
- return;
73
+ return state.info || null;
27
74
  }
28
- await (0, bundleInfo_1.updateBundleInfo)({ pendingApply: false, installedAt: new Date().toISOString() });
75
+ const appliedInfo = {
76
+ ...state.info,
77
+ pendingApply: false,
78
+ installedAt: new Date().toISOString(),
79
+ };
80
+ await (0, bundleInfo_1.updateBundleInfo)(appliedInfo);
29
81
  // Fire-and-forget: don't block the startup path for server reporting
30
82
  (0, reporting_1.reportInstalledIfReady)({
31
83
  hasBundle: true,
32
- info: state.info ? { ...state.info, pendingApply: false } : state.info,
84
+ info: appliedInfo,
33
85
  }).catch(() => { });
86
+ return appliedInfo;
34
87
  };
35
88
  exports.reconcileAppliedBundleOnLaunch = reconcileAppliedBundleOnLaunch;
36
89
  const applyUpdate = async (onStatusUpdate, onBeforeRestart) => {
package/lib/metro.d.ts CHANGED
@@ -12,7 +12,7 @@ export type WithBundleDropOptions = {
12
12
  export type WithBundleDropExpoOptions = WithBundleDropOptions;
13
13
  /**
14
14
  * Preserves a bare React Native Metro config and resolves Bundle Drop through
15
- * the project-owned, package-validated generated bootstrap.
15
+ * the project-owned, package-validated runtime-delivery lockfile.
16
16
  */
17
17
  export declare function withBundleDrop<T extends BundleDropMetroConfig>(config: T, options?: WithBundleDropOptions): T;
18
18
  export declare const withBundleDropBare: typeof withBundleDrop;
package/lib/metro.js CHANGED
@@ -24,7 +24,7 @@ const loadBaseConfig = (projectRoot) => {
24
24
  return config;
25
25
  };
26
26
  const resolveRuntimeDelivery = (projectRoot, baseConfig) => {
27
- const generated = (0, bootstrapConfig_1.readGeneratedRuntimeDeliveryBootstrap)({
27
+ const bootstrap = (0, bootstrapConfig_1.readRuntimeDeliveryBootstrap)({
28
28
  projectRoot,
29
29
  expectedIdentity: {
30
30
  serverUrl: baseConfig.serverUrl,
@@ -32,7 +32,7 @@ const resolveRuntimeDelivery = (projectRoot, baseConfig) => {
32
32
  projectSlug: baseConfig.project.slug,
33
33
  },
34
34
  });
35
- return generated?.runtimeDelivery;
35
+ return bootstrap?.runtimeDelivery;
36
36
  };
37
37
  const writeGeneratedRuntimeConfig = (params) => {
38
38
  const generatedDirectory = path_1.default.join(params.projectRoot, '.bundle-drop', 'generated');
@@ -46,6 +46,7 @@ const writeGeneratedRuntimeConfig = (params) => {
46
46
  generatedFields.push(` runtimeDelivery: ${JSON.stringify(params.runtimeDelivery)},`);
47
47
  }
48
48
  const content = [
49
+ '/* eslint-disable */',
49
50
  "'use strict';",
50
51
  '',
51
52
  "const baseConfig = require('../../bundle.drop.config.js');",
@@ -72,7 +73,7 @@ const mergeMetroAlias = (config, generatedConfigPath) => ({
72
73
  });
73
74
  /**
74
75
  * Preserves a bare React Native Metro config and resolves Bundle Drop through
75
- * the project-owned, package-validated generated bootstrap.
76
+ * the project-owned, package-validated runtime-delivery lockfile.
76
77
  */
77
78
  function withBundleDrop(config, options = {}) {
78
79
  const projectRoot = path_1.default.resolve(options.projectRoot || process.cwd());