@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
@@ -0,0 +1,92 @@
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.resolveNativeRuntimeIdentity = resolveNativeRuntimeIdentity;
7
+ exports.writeNativeRuntimeIdentity = writeNativeRuntimeIdentity;
8
+ exports.parseNativeRuntimeIdentityArguments = parseNativeRuntimeIdentityArguments;
9
+ const fs_extra_1 = __importDefault(require("fs-extra"));
10
+ const path_1 = __importDefault(require("path"));
11
+ const expo_1 = require("../../../expo");
12
+ function resolveNativeRuntimeIdentity(projectRoot, platform) {
13
+ const authority = (0, expo_1.resolveBundleDropRuntimeVersionAuthority)(projectRoot, platform);
14
+ if (authority.source === 'expo') {
15
+ return { schemaVersion: 1, platform, source: 'expo' };
16
+ }
17
+ return {
18
+ schemaVersion: 1,
19
+ platform,
20
+ source: 'bundle-drop',
21
+ runtimeVersion: authority.runtimeVersion,
22
+ };
23
+ }
24
+ function writeAtomically(outputPath, content) {
25
+ const absoluteOutputPath = path_1.default.resolve(outputPath);
26
+ fs_extra_1.default.ensureDirSync(path_1.default.dirname(absoluteOutputPath));
27
+ const temporaryPath = path_1.default.join(path_1.default.dirname(absoluteOutputPath), `.${path_1.default.basename(absoluteOutputPath)}-${process.pid}-${Date.now()}.tmp`);
28
+ try {
29
+ fs_extra_1.default.writeFileSync(temporaryPath, content, 'utf8');
30
+ const descriptor = fs_extra_1.default.openSync(temporaryPath, 'r');
31
+ try {
32
+ fs_extra_1.default.fsyncSync(descriptor);
33
+ }
34
+ finally {
35
+ fs_extra_1.default.closeSync(descriptor);
36
+ }
37
+ fs_extra_1.default.renameSync(temporaryPath, absoluteOutputPath);
38
+ }
39
+ catch (error) {
40
+ try {
41
+ fs_extra_1.default.removeSync(temporaryPath);
42
+ }
43
+ catch {
44
+ // Preserve the original failure.
45
+ }
46
+ throw error;
47
+ }
48
+ }
49
+ function writeNativeRuntimeIdentity(options) {
50
+ const identity = resolveNativeRuntimeIdentity(options.projectRoot, options.platform);
51
+ const content = `${JSON.stringify(identity)}\n`;
52
+ if (options.outputPath) {
53
+ writeAtomically(options.outputPath, content);
54
+ }
55
+ return identity;
56
+ }
57
+ function parseNativeRuntimeIdentityArguments(argv) {
58
+ const values = new Map();
59
+ for (let index = 0; index < argv.length; index += 2) {
60
+ const flag = argv[index];
61
+ const value = argv[index + 1];
62
+ if (!['--project-root', '--platform', '--output'].includes(flag) || !value) {
63
+ throw new Error('Usage: write-runtime-identity --project-root <path> --platform ios|android [--output <path>]');
64
+ }
65
+ if (values.has(flag))
66
+ throw new Error(`Duplicate argument ${flag}.`);
67
+ values.set(flag, value);
68
+ }
69
+ const projectRoot = values.get('--project-root');
70
+ const platform = values.get('--platform');
71
+ if (!projectRoot || (platform !== 'ios' && platform !== 'android')) {
72
+ throw new Error('Usage: write-runtime-identity --project-root <path> --platform ios|android [--output <path>]');
73
+ }
74
+ return {
75
+ projectRoot,
76
+ platform,
77
+ ...(values.get('--output') ? { outputPath: values.get('--output') } : {}),
78
+ };
79
+ }
80
+ /* istanbul ignore next */
81
+ if (require.main === module) {
82
+ try {
83
+ const identity = writeNativeRuntimeIdentity(parseNativeRuntimeIdentityArguments(process.argv.slice(2)));
84
+ if (!process.argv.includes('--output')) {
85
+ process.stdout.write(`${JSON.stringify(identity)}\n`);
86
+ }
87
+ }
88
+ catch (error) {
89
+ process.stderr.write(`${error.message}\n`);
90
+ process.exitCode = 1;
91
+ }
92
+ }
@@ -1,4 +1,6 @@
1
- export default function upload(platform: string, options: {
1
+ import { spawnSync } from 'child_process';
2
+ import { type ModuleResolver } from '../../scripts/resolveModule';
3
+ type UploadOptions = {
2
4
  plistFile?: string;
3
5
  version?: string;
4
6
  channel?: string;
@@ -9,4 +11,12 @@ export default function upload(platform: string, options: {
9
11
  sourcemap?: boolean;
10
12
  artifactDir?: string;
11
13
  buildReceipt?: string;
12
- }): Promise<void>;
14
+ };
15
+ type UploadDependencies = {
16
+ packageRoot: string;
17
+ spawnProcess: typeof spawnSync;
18
+ resolveModule: ModuleResolver;
19
+ };
20
+ export declare function runUpload(platform: string, options: UploadOptions, dependencies?: UploadDependencies): Promise<void>;
21
+ export default function upload(platform: string, options: UploadOptions): Promise<void>;
22
+ export {};
@@ -36,6 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.runUpload = runUpload;
39
40
  exports.default = upload;
40
41
  const axios_1 = __importDefault(require("axios"));
41
42
  const child_process_1 = require("child_process");
@@ -46,6 +47,8 @@ const plist = __importStar(require("plist"));
46
47
  const ui_1 = require("../utils/ui");
47
48
  const resolve_ios_version_1 = require("../../scripts/resolve-ios-version");
48
49
  const expo_1 = require("../../expo");
50
+ const resolveModule_1 = require("../../scripts/resolveModule");
51
+ const serverUrl_1 = require("../serverUrl");
49
52
  const DOCS_INSTALLATION_URL = 'https://bundledrop.app/docs/installation';
50
53
  const DOCS_UPLOADING_URL = 'https://bundledrop.app/docs/uploading';
51
54
  const DOCS_CI_CD_URL = 'https://bundledrop.app/docs/ci-cd';
@@ -55,7 +58,23 @@ const BUNDLE_DROP_ARTIFACT_FILES = [
55
58
  'main.jsbundle.map',
56
59
  'bundle-drop-result.json',
57
60
  ];
58
- const getPackageRoot = () => process.env.BUNDLE_DROP_PACKAGE_ROOT_OVERRIDE || path.resolve(__dirname, '..', '..', '..');
61
+ const defaultUploadDependencies = () => ({
62
+ packageRoot: path.resolve(__dirname, '..', '..', '..'),
63
+ spawnProcess: child_process_1.spawnSync,
64
+ resolveModule: resolveModule_1.resolveModuleFrom,
65
+ });
66
+ const assertPathInside = (targetPath, parentPath, label) => {
67
+ const resolvedParent = path.resolve(parentPath);
68
+ const resolvedTarget = path.resolve(targetPath);
69
+ const relative = path.relative(resolvedParent, resolvedTarget);
70
+ const escapesParent = relative === '..' ||
71
+ relative.startsWith(`..${path.sep}`) ||
72
+ path.isAbsolute(relative);
73
+ if (!escapesParent) {
74
+ return;
75
+ }
76
+ throw new Error(`${label} escaped its generated output directory: ${resolvedTarget}`);
77
+ };
59
78
  const readPackageVersion = (packageRoot) => {
60
79
  try {
61
80
  const packageJson = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8'));
@@ -114,7 +133,7 @@ const bareArtifactPaths = (packageRoot, platform) => {
114
133
  zipPath: path.join(outputDir, `bundle-${platform}.zip`),
115
134
  };
116
135
  };
117
- async function upload(platform, options) {
136
+ async function runUpload(platform, options, dependencies = defaultUploadDependencies()) {
118
137
  console.log(); // blank line
119
138
  ui_1.log.info('🚀 React Native OTA Upload Initialized');
120
139
  const projectRoot = process.cwd();
@@ -165,7 +184,26 @@ async function upload(platform, options) {
165
184
  `CI/CD tokens: ${DOCS_CI_CD_URL}`);
166
185
  process.exit(1);
167
186
  }
168
- token = JSON.parse(fs.readFileSync(authPath, 'utf-8')).token;
187
+ let storedAuth;
188
+ try {
189
+ storedAuth = JSON.parse(fs.readFileSync(authPath, 'utf-8'));
190
+ }
191
+ catch {
192
+ ui_1.log.error('❌ Failed to read CLI auth session. Run `bundle-drop login` again or pass --token.');
193
+ process.exit(1);
194
+ }
195
+ if (!storedAuth?.token) {
196
+ ui_1.log.error('❌ CLI auth session is missing a token. Run `bundle-drop login` again or pass --token.');
197
+ process.exit(1);
198
+ }
199
+ try {
200
+ (0, serverUrl_1.assertMatchingServerOrigin)(serverUrl, storedAuth.serverUrl || storedAuth.baseUrl);
201
+ }
202
+ catch (error) {
203
+ ui_1.log.error(`❌ ${error.message}`);
204
+ process.exit(1);
205
+ }
206
+ token = storedAuth.token;
169
207
  }
170
208
  // Validate channel
171
209
  const channel = options.channel;
@@ -271,7 +309,7 @@ async function upload(platform, options) {
271
309
  ui_1.log.label('App Version', version);
272
310
  console.log();
273
311
  ui_1.log.arrow(`Bundling ${platform} app...`);
274
- const packageRoot = getPackageRoot();
312
+ const packageRoot = dependencies.packageRoot;
275
313
  const packageVersion = readPackageVersion(packageRoot);
276
314
  const compiledBundleScript = path.join(packageRoot, 'lib', 'scripts', 'bundle.js');
277
315
  const tsBundleScript = path.join(packageRoot, 'src', 'scripts', 'bundle.ts');
@@ -289,17 +327,30 @@ async function upload(platform, options) {
289
327
  });
290
328
  }
291
329
  else {
292
- const bundleCommand = fs.existsSync(compiledBundleScript)
293
- ? `node "${compiledBundleScript}"`
294
- : `ts-node "${tsBundleScript}"`;
295
- const sourcemapArg = options.sourcemap ? ' --sourcemap' : '';
296
- (0, child_process_1.execSync)(`${bundleCommand} ${platform}${sourcemapArg}`, {
330
+ const useCompiledScript = fs.existsSync(compiledBundleScript);
331
+ const script = useCompiledScript
332
+ ? compiledBundleScript
333
+ : dependencies.resolveModule('ts-node/dist/bin.js', [packageRoot, __dirname]);
334
+ const args = [
335
+ script,
336
+ ...(useCompiledScript ? [] : [tsBundleScript]),
337
+ platform,
338
+ ];
339
+ if (options.sourcemap)
340
+ args.push('--sourcemap');
341
+ const result = dependencies.spawnProcess(process.execPath, args, {
297
342
  stdio: 'inherit',
343
+ shell: false,
298
344
  env: {
299
345
  ...process.env,
300
346
  BUNDLE_DROP_APP_VERSION: version,
301
347
  },
302
348
  });
349
+ if (result.error)
350
+ throw result.error;
351
+ if (result.status !== 0) {
352
+ throw new Error(`Bundle process exited with status ${result.status}`);
353
+ }
303
354
  }
304
355
  }
305
356
  catch (error) {
@@ -425,6 +476,10 @@ async function upload(platform, options) {
425
476
  }
426
477
  finally {
427
478
  try {
479
+ const generatedRoot = isExpoProject
480
+ ? path.join(projectRoot, '.bundle-drop', 'artifacts')
481
+ : path.join(packageRoot, 'dist');
482
+ assertPathInside(artifact.outputDir, generatedRoot, 'Artifact output');
428
483
  const cleanupFiles = [
429
484
  artifact.zipPath,
430
485
  artifact.metadataPath,
@@ -436,12 +491,17 @@ async function upload(platform, options) {
436
491
  const expoExportDirectory = artifact.expoExportDirectory ??
437
492
  path.join(packageRoot, 'dist', `expo-export-${platform}`);
438
493
  for (const file of cleanupFiles) {
439
- if (file && fs.existsSync(file))
440
- fs.unlinkSync(file);
494
+ if (file) {
495
+ assertPathInside(file, artifact.outputDir, 'Artifact file');
496
+ if (fs.existsSync(file))
497
+ fs.unlinkSync(file);
498
+ }
441
499
  }
500
+ assertPathInside(assetsPath, artifact.outputDir, 'Artifact assets');
442
501
  if (fs.existsSync(assetsPath)) {
443
502
  fs.rmSync(assetsPath, { recursive: true, force: true });
444
503
  }
504
+ assertPathInside(expoExportDirectory, generatedRoot, 'Expo export');
445
505
  if (fs.existsSync(expoExportDirectory)) {
446
506
  fs.rmSync(expoExportDirectory, { recursive: true, force: true });
447
507
  }
@@ -456,3 +516,6 @@ async function upload(platform, options) {
456
516
  }
457
517
  }
458
518
  }
519
+ function upload(platform, options) {
520
+ return runUpload(platform, options);
521
+ }
@@ -0,0 +1,3 @@
1
+ export declare const DEFAULT_SERVER_URL = "https://api.bundledrop.app";
2
+ export declare const normalizeServerUrl: (value?: string) => string;
3
+ export declare const assertMatchingServerOrigin: (requestServerUrl: string, authenticatedServerUrl: string | undefined) => void;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.assertMatchingServerOrigin = exports.normalizeServerUrl = exports.DEFAULT_SERVER_URL = void 0;
4
+ exports.DEFAULT_SERVER_URL = 'https://api.bundledrop.app';
5
+ const normalizeServerUrl = (value) => {
6
+ const serverUrl = value || exports.DEFAULT_SERVER_URL;
7
+ let parsed;
8
+ try {
9
+ parsed = new URL(serverUrl);
10
+ }
11
+ catch {
12
+ throw new Error('Bundle Drop serverUrl must be an HTTP(S) URL without embedded credentials.');
13
+ }
14
+ if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password) {
15
+ throw new Error('Bundle Drop serverUrl must be an HTTP(S) URL without embedded credentials.');
16
+ }
17
+ return serverUrl.replace(/\/+$/, '');
18
+ };
19
+ exports.normalizeServerUrl = normalizeServerUrl;
20
+ const assertMatchingServerOrigin = (requestServerUrl, authenticatedServerUrl) => {
21
+ if (!authenticatedServerUrl) {
22
+ throw new Error('The stored CLI login is not bound to a server. Run `bundle-drop login` again or pass --token explicitly.');
23
+ }
24
+ const requestOrigin = new URL((0, exports.normalizeServerUrl)(requestServerUrl)).origin;
25
+ const authenticatedOrigin = new URL((0, exports.normalizeServerUrl)(authenticatedServerUrl)).origin;
26
+ if (requestOrigin !== authenticatedOrigin) {
27
+ throw new Error(`The stored CLI login belongs to ${authenticatedOrigin}, but this project targets ${requestOrigin}. ` +
28
+ 'Run `bundle-drop login` for this server or pass --token explicitly.');
29
+ }
30
+ };
31
+ exports.assertMatchingServerOrigin = assertMatchingServerOrigin;
@@ -24,5 +24,7 @@ export type BundleInfo = {
24
24
  runtimeVersion?: string;
25
25
  };
26
26
  export declare function readBundleInfo(): Promise<BundleInfo | null>;
27
+ export declare function writeBundleInfoDurably(info: BundleInfo): Promise<void>;
27
28
  export declare function writeBundleInfo(info: BundleInfo): Promise<void>;
28
29
  export declare function updateBundleInfo(partial: Partial<BundleInfo>): Promise<void>;
30
+ export declare function deleteBundleInfo(): Promise<void>;
package/lib/bundleInfo.js CHANGED
@@ -4,8 +4,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.readBundleInfo = readBundleInfo;
7
+ exports.writeBundleInfoDurably = writeBundleInfoDurably;
7
8
  exports.writeBundleInfo = writeBundleInfo;
8
9
  exports.updateBundleInfo = updateBundleInfo;
10
+ exports.deleteBundleInfo = deleteBundleInfo;
9
11
  const fs_1 = __importDefault(require("./native/fs"));
10
12
  const BUNDLE_INFO_PATH = `${fs_1.default.DocumentDirectoryPath}/bundle-info.json`;
11
13
  async function readBundleInfo() {
@@ -20,9 +22,12 @@ async function readBundleInfo() {
20
22
  return null;
21
23
  }
22
24
  }
25
+ async function writeBundleInfoDurably(info) {
26
+ await fs_1.default.writeFile(BUNDLE_INFO_PATH, JSON.stringify(info, null, 2), 'utf8');
27
+ }
23
28
  async function writeBundleInfo(info) {
24
29
  try {
25
- await fs_1.default.writeFile(BUNDLE_INFO_PATH, JSON.stringify(info, null, 2), 'utf8');
30
+ await writeBundleInfoDurably(info);
26
31
  }
27
32
  catch (e) {
28
33
  console.warn('⚠️ Failed to write bundle-info.json', e);
@@ -32,3 +37,13 @@ async function updateBundleInfo(partial) {
32
37
  const existing = (await readBundleInfo()) || {};
33
38
  await writeBundleInfo({ ...existing, ...partial });
34
39
  }
40
+ async function deleteBundleInfo() {
41
+ try {
42
+ if (await fs_1.default.exists(BUNDLE_INFO_PATH)) {
43
+ await fs_1.default.unlink(BUNDLE_INFO_PATH);
44
+ }
45
+ }
46
+ catch (e) {
47
+ console.warn('⚠️ Failed to delete bundle-info.json', e);
48
+ }
49
+ }
package/lib/context.js CHANGED
@@ -29,6 +29,16 @@ exports.runtimeVersion = typeof platformRuntimeVersion === 'string'
29
29
  : (0, nativeIdentity_1.resolveExpoNativeRuntimeVersion)(platformRuntimeVersion.source)
30
30
  : undefined;
31
31
  exports.defaultChannel = exports.config.defaultChannel || 'develop';
32
+ const configuredMaxCrashCount = exports.config.rollback?.maxCrashCount ?? 3;
33
+ if (!Number.isSafeInteger(configuredMaxCrashCount) ||
34
+ configuredMaxCrashCount < 0 ||
35
+ configuredMaxCrashCount > 2147483647) {
36
+ throw new Error('[BundleDrop] rollback.maxCrashCount must be a non-negative 32-bit integer.');
37
+ }
38
+ const configuredHealthyAfterSec = exports.config.rollback?.healthyAfterSec ?? 0;
39
+ if (!Number.isFinite(configuredHealthyAfterSec) || configuredHealthyAfterSec < 0) {
40
+ throw new Error('[BundleDrop] rollback.healthyAfterSec must be a finite non-negative number.');
41
+ }
32
42
  exports.BUNDLE_DROP_ROOT = exports.isIOS
33
43
  ? `${fs_1.default.LibraryDirectoryPath}/bundle-drop`
34
44
  : `${fs_1.default.DocumentDirectoryPath}/bundle-drop`;
@@ -43,8 +53,8 @@ exports.bundleDropConfig = {
43
53
  org: { slug: exports.config.org.slug },
44
54
  project: { name: exports.config.project.name, slug: exports.config.project.slug },
45
55
  rollback: {
46
- maxCrashCount: exports.config.rollback?.maxCrashCount ?? 3,
56
+ maxCrashCount: configuredMaxCrashCount,
47
57
  healthCheckMode: exports.config.rollback?.healthCheckMode === 'manual' ? 'manual' : 'auto',
48
- healthyAfterSec: exports.config.rollback?.healthyAfterSec ?? 0,
58
+ healthyAfterSec: configuredHealthyAfterSec,
49
59
  },
50
60
  };
@@ -1,17 +1 @@
1
- export type BundlePointer = {
2
- hash: string;
3
- bundlePath: string;
4
- updatedAt: string;
5
- };
6
- export declare function readCurrentBundlePointer(): Promise<BundlePointer | null>;
7
- export declare function readPreviousBundlePointer(): Promise<BundlePointer | null>;
8
- export declare function writeCurrentBundlePointer(pointer: BundlePointer): Promise<void>;
9
- export declare function writePreviousBundlePointer(pointer: BundlePointer): Promise<void>;
10
- export declare function restorePreviousBundlePointer(pointer: BundlePointer | null): Promise<void>;
11
- export declare function setCurrentBundlePointer(_bundlePath: string, hash: string, options?: {
12
- setPrevious?: boolean;
13
- }): Promise<void>;
14
- export declare function rollbackToPreviousPointer(): Promise<BundlePointer | null>;
15
- export declare function deleteCurrentBundlePointer(): Promise<void>;
16
- export declare function deletePreviousBundlePointer(): Promise<void>;
17
- export declare function clearCurrentBundlePointer(): Promise<void>;
1
+ export declare function readCurrentBundleHash(): Promise<string | null>;
@@ -3,24 +3,12 @@ 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.readCurrentBundlePointer = readCurrentBundlePointer;
7
- exports.readPreviousBundlePointer = readPreviousBundlePointer;
8
- exports.writeCurrentBundlePointer = writeCurrentBundlePointer;
9
- exports.writePreviousBundlePointer = writePreviousBundlePointer;
10
- exports.restorePreviousBundlePointer = restorePreviousBundlePointer;
11
- exports.setCurrentBundlePointer = setCurrentBundlePointer;
12
- exports.rollbackToPreviousPointer = rollbackToPreviousPointer;
13
- exports.deleteCurrentBundlePointer = deleteCurrentBundlePointer;
14
- exports.deletePreviousBundlePointer = deletePreviousBundlePointer;
15
- exports.clearCurrentBundlePointer = clearCurrentBundlePointer;
6
+ exports.readCurrentBundleHash = readCurrentBundleHash;
16
7
  const fs_1 = __importDefault(require("../native/fs"));
17
8
  const context_1 = require("../context");
18
- const fsUtils_1 = require("./fsUtils");
19
9
  const CURRENT_POINTER_PATH = `${context_1.BUNDLE_DROP_ROOT}/current.json`;
20
- const PREVIOUS_POINTER_PATH = `${context_1.BUNDLE_DROP_ROOT}/previous.json`;
21
10
  const BUNDLE_HASH_PATTERN = /^[a-f0-9]{64}$/;
22
- const bundlePathForHash = (hash) => `${context_1.BUNDLE_DROP_ROOT}/bundles/${hash}/main.jsbundle`;
23
- async function readPointer(path) {
11
+ async function readPointerHash(path) {
24
12
  try {
25
13
  if (!(await fs_1.default.exists(path)))
26
14
  return null;
@@ -28,88 +16,12 @@ async function readPointer(path) {
28
16
  const parsed = JSON.parse(raw);
29
17
  if (!BUNDLE_HASH_PATTERN.test(parsed?.hash ?? ''))
30
18
  return null;
31
- return {
32
- hash: parsed.hash,
33
- bundlePath: bundlePathForHash(parsed.hash),
34
- updatedAt: typeof parsed.updatedAt === 'string' ? parsed.updatedAt : '',
35
- };
19
+ return parsed.hash;
36
20
  }
37
21
  catch {
38
22
  return null;
39
23
  }
40
24
  }
41
- async function readCurrentBundlePointer() {
42
- return readPointer(CURRENT_POINTER_PATH);
43
- }
44
- async function readPreviousBundlePointer() {
45
- return readPointer(PREVIOUS_POINTER_PATH);
46
- }
47
- async function writeCurrentBundlePointer(pointer) {
48
- assertCanonicalPointerHash(pointer.hash);
49
- const root = context_1.BUNDLE_DROP_ROOT;
50
- await (0, fsUtils_1.ensureDir)(root);
51
- await (0, fsUtils_1.atomicWriteJson)(CURRENT_POINTER_PATH, pointerJson(pointer));
52
- }
53
- async function writePreviousBundlePointer(pointer) {
54
- assertCanonicalPointerHash(pointer.hash);
55
- const root = context_1.BUNDLE_DROP_ROOT;
56
- await (0, fsUtils_1.ensureDir)(root);
57
- await (0, fsUtils_1.atomicWriteJson)(PREVIOUS_POINTER_PATH, pointerJson(pointer));
58
- }
59
- async function restorePreviousBundlePointer(pointer) {
60
- if (pointer) {
61
- await writePreviousBundlePointer({ ...pointer, updatedAt: new Date().toISOString() });
62
- return;
63
- }
64
- await deletePreviousBundlePointer();
65
- }
66
- async function setCurrentBundlePointer(_bundlePath, hash, options) {
67
- assertCanonicalPointerHash(hash);
68
- const root = context_1.BUNDLE_DROP_ROOT;
69
- await (0, fsUtils_1.ensureDir)(root);
70
- const current = await readCurrentBundlePointer();
71
- if (options?.setPrevious !== false && current?.hash && current?.bundlePath) {
72
- await writePreviousBundlePointer({ ...current, updatedAt: new Date().toISOString() });
73
- }
74
- await writeCurrentBundlePointer({
75
- hash,
76
- bundlePath: bundlePathForHash(hash),
77
- updatedAt: new Date().toISOString(),
78
- });
79
- }
80
- function pointerJson(pointer) {
81
- return {
82
- hash: pointer.hash,
83
- updatedAt: pointer.updatedAt,
84
- };
85
- }
86
- function assertCanonicalPointerHash(hash) {
87
- if (!BUNDLE_HASH_PATTERN.test(hash)) {
88
- throw new Error('Bundle pointer hash must be a canonical 64-character lowercase SHA-256 hash');
89
- }
90
- }
91
- async function rollbackToPreviousPointer() {
92
- const previous = await readPreviousBundlePointer();
93
- if (!previous)
94
- return null;
95
- await writeCurrentBundlePointer({ ...previous, updatedAt: new Date().toISOString() });
96
- return previous;
97
- }
98
- async function deleteCurrentBundlePointer() {
99
- if (await fs_1.default.exists(CURRENT_POINTER_PATH)) {
100
- await fs_1.default.unlink(CURRENT_POINTER_PATH);
101
- }
102
- }
103
- async function deletePreviousBundlePointer() {
104
- if (await fs_1.default.exists(PREVIOUS_POINTER_PATH)) {
105
- await fs_1.default.unlink(PREVIOUS_POINTER_PATH);
106
- }
107
- }
108
- async function clearCurrentBundlePointer() {
109
- try {
110
- await deleteCurrentBundlePointer();
111
- }
112
- catch {
113
- // Best-effort cleanup for callers that do not need strict rollback semantics.
114
- }
25
+ async function readCurrentBundleHash() {
26
+ return readPointerHash(CURRENT_POINTER_PATH);
115
27
  }
@@ -68,8 +68,8 @@ const finalizeInstall = async (verifiedTempDir, fileNames, hash, platform, statu
68
68
  existingManifest = await (0, bundleVerification_1.verifyBundleDir)(bundleDir, hash, platform);
69
69
  }
70
70
  catch (e) {
71
- const currentPointer = await (0, bundlePointer_1.readCurrentBundlePointer)();
72
- if (currentPointer?.hash === hash) {
71
+ const currentHash = await (0, bundlePointer_1.readCurrentBundleHash)();
72
+ if (currentHash === hash) {
73
73
  throw new Error('Active bundle folder failed verification');
74
74
  }
75
75
  }
@@ -82,8 +82,8 @@ const finalizeInstall = async (verifiedTempDir, fileNames, hash, platform, statu
82
82
  catch { /* best-effort cleanup */ }
83
83
  return { bundlePath, metadataFromZip };
84
84
  }
85
- const currentPointer = await (0, bundlePointer_1.readCurrentBundlePointer)();
86
- if (currentPointer?.hash === hash) {
85
+ const currentHash = await (0, bundlePointer_1.readCurrentBundleHash)();
86
+ if (currentHash === hash) {
87
87
  throw new Error('Active bundle folder failed verification');
88
88
  }
89
89
  await fs_1.default.unlink(bundleDir);
@@ -3,21 +3,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.installBundle = exports.downloadUpdate = void 0;
4
4
  const context_1 = require("../context");
5
5
  const bundleInfo_1 = require("../bundleInfo");
6
- const bundlePointer_1 = require("../fs/bundlePointer");
7
6
  const installFromZip_1 = require("../install/installFromZip");
8
7
  const patchTransport_1 = require("../patch-engine/patchTransport");
9
- const bundleDropNative_1 = require("../native/bundleDropNative");
10
8
  const updateCheck_1 = require("./updateCheck");
11
9
  const errors_1 = require("../errors");
12
10
  const rollbackState_1 = require("./rollbackState");
13
11
  const artifactCapability_1 = require("../runtime-delivery/artifactCapability");
14
- async function restoreCurrentPointer(pointer) {
15
- if (pointer) {
16
- await (0, bundlePointer_1.writeCurrentBundlePointer)({ ...pointer, updatedAt: new Date().toISOString() });
17
- return;
18
- }
19
- await (0, bundlePointer_1.deleteCurrentBundlePointer)();
20
- }
21
12
  function isSameRuntimeDeliverySelection(selected, refreshed) {
22
13
  if (!refreshed ||
23
14
  refreshed.action !== 'INSTALL' ||
@@ -211,11 +202,7 @@ async function downloadAndStageUpdate(options, onStatusUpdate) {
211
202
  const installedHash = hash;
212
203
  statusCb?.('✅ Update downloaded. Will apply on next launch or when you call applyUpdate().');
213
204
  // Persist installed metadata for future skip logic.
214
- const [previousInfo, previousCurrentPointer, previousRollbackPointer] = await Promise.all([
215
- (0, bundleInfo_1.readBundleInfo)(),
216
- (0, bundlePointer_1.readCurrentBundlePointer)(),
217
- (0, bundlePointer_1.readPreviousBundlePointer)(),
218
- ]);
205
+ const previousInfo = await (0, bundleInfo_1.readBundleInfo)();
219
206
  const installedInfo = {
220
207
  bundleVersion: serverBundleVersion ?? metadataFromZip.bundleVersion,
221
208
  version: serverVersion ?? metadataFromZip.version,
@@ -228,21 +215,39 @@ async function downloadAndStageUpdate(options, onStatusUpdate) {
228
215
  lastInstalledReportedHash: previousInfo?.lastInstalledReportedHash,
229
216
  installedReportedHashes: previousInfo?.installedReportedHashes,
230
217
  };
231
- await (0, bundlePointer_1.setCurrentBundlePointer)(bundlePath, installedHash);
218
+ let candidateActivated = false;
232
219
  try {
233
- const resolvedBundlePath = await (0, bundleDropNative_1.getDownloadedBundlePathNative)();
234
- if (resolvedBundlePath !== bundlePath) {
220
+ const activation = await (0, rollbackState_1.activateStartupCandidate)(installedHash);
221
+ candidateActivated = activation !== null;
222
+ if (!activation) {
223
+ throw new errors_1.BundleDropError({
224
+ message: 'Installed bundle requires native startup recovery support',
225
+ code: 'INSTALL_FAILED',
226
+ step: 'install',
227
+ context: { channelName, platform, hash },
228
+ });
229
+ }
230
+ if (activation.hash !== installedHash || activation.bundlePath !== bundlePath) {
235
231
  throw new errors_1.BundleDropError({
236
232
  message: 'Installed bundle was not accepted by the native resolver',
237
233
  code: 'INSTALL_FAILED',
238
234
  step: 'install',
239
- context: { channelName, platform, hash, expectedBundlePath: bundlePath, resolvedBundlePath },
235
+ context: {
236
+ channelName,
237
+ platform,
238
+ hash,
239
+ expectedBundlePath: bundlePath,
240
+ resolvedBundlePath: activation.bundlePath,
241
+ resolvedHash: activation.hash,
242
+ },
240
243
  });
241
244
  }
245
+ await (0, bundleInfo_1.writeBundleInfoDurably)(installedInfo);
242
246
  }
243
247
  catch (nativeError) {
244
- await restoreCurrentPointer(previousCurrentPointer);
245
- await (0, bundlePointer_1.restorePreviousBundlePointer)(previousRollbackPointer);
248
+ if (candidateActivated) {
249
+ await (0, rollbackState_1.rollbackStartupBundle)(false).catch(() => false);
250
+ }
246
251
  if (nativeError instanceof errors_1.BundleDropError) {
247
252
  throw nativeError;
248
253
  }
@@ -254,8 +259,6 @@ async function downloadAndStageUpdate(options, onStatusUpdate) {
254
259
  cause: nativeError,
255
260
  });
256
261
  }
257
- await (0, bundleInfo_1.writeBundleInfo)(installedInfo);
258
- await (0, rollbackState_1.markCandidateActivated)(installedHash);
259
262
  return { status: 'staged', bundlePath, hash: installedHash };
260
263
  }
261
264
  catch (err) {
@@ -1,5 +1,12 @@
1
1
  import { BundleInfo } from '../bundleInfo';
2
- import type { FailedBundleRecord } from './rollbackState';
2
+ export type FailedBundleRecord = {
3
+ reason: 'crash_loop';
4
+ failedAt: number;
5
+ crashCount?: number;
6
+ channelName?: string;
7
+ runtimeVersion?: string;
8
+ previousHash?: string;
9
+ };
3
10
  export declare function reportInstalledIfReady(state?: {
4
11
  hasBundle?: boolean;
5
12
  info?: BundleInfo | null;