@gfean/react-native-bundle-drop 0.3.2 → 0.3.5

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 (51) hide show
  1. package/BundleDrop.podspec +4 -1
  2. package/LICENSE +15 -0
  3. package/README.md +120 -253
  4. package/android/build.gradle +91 -1
  5. package/android/gradle.properties +1 -0
  6. package/android/src/main/java/com/bundledrop/BundleDropFileOps.kt +131 -0
  7. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +65 -89
  8. package/android/src/main/java/com/bundledrop/BundleDropOtaResolver.kt +93 -0
  9. package/ios/BundleDropBridge.m +14 -0
  10. package/ios/BundleDropFileOps.swift +220 -0
  11. package/ios/BundleDropLocator.swift +33 -44
  12. package/ios/BundleDropModule.swift +65 -15
  13. package/ios/BundleDropOtaResolver.swift +112 -0
  14. package/ios/BundleDropZipExtractor.h +13 -0
  15. package/ios/BundleDropZipExtractor.m +226 -0
  16. package/lib/CLI/cli.js +15 -3
  17. package/lib/CLI/scripts/init-config.js +12 -5
  18. package/lib/CLI/scripts/init-native-config.js +17 -9
  19. package/lib/CLI/scripts/post-init.js +9 -3
  20. package/lib/CLI/scripts/upload-cli.js +26 -9
  21. package/lib/api/types.d.ts +4 -3
  22. package/lib/bundleInfo.d.ts +12 -0
  23. package/lib/context.d.ts +17 -0
  24. package/lib/context.js +3 -0
  25. package/lib/errors.d.ts +25 -0
  26. package/lib/errors.js +26 -1
  27. package/lib/fs/fsUtils.d.ts +1 -2
  28. package/lib/fs/fsUtils.js +12 -27
  29. package/lib/fs/userProperties.d.ts +25 -4
  30. package/lib/fs/userProperties.js +51 -7
  31. package/lib/index.d.ts +1 -0
  32. package/lib/install/installFromZip.d.ts +1 -1
  33. package/lib/install/installFromZip.js +47 -42
  34. package/lib/loadConfig.d.ts +19 -0
  35. package/lib/loadConfig.js +11 -7
  36. package/lib/manager/downloadAndInstall.js +7 -25
  37. package/lib/manager/reporting.js +2 -2
  38. package/lib/manager/rollbackState.d.ts +3 -3
  39. package/lib/manager/rollbackState.js +6 -19
  40. package/lib/manager/updateCheck.js +2 -2
  41. package/lib/native/fs.d.ts +6 -0
  42. package/lib/native/fs.js +27 -0
  43. package/lib/runtime/initState.d.ts +2 -2
  44. package/lib/runtime/service.js +2 -0
  45. package/lib/scripts/bundle.js +2 -2
  46. package/lib/scripts/resolve-ios-version.d.ts +2 -0
  47. package/lib/scripts/resolve-ios-version.js +74 -0
  48. package/lib/scripts/upload-bundle.js +10 -4
  49. package/lib/types.d.ts +3 -0
  50. package/package.json +53 -16
  51. package/CLIENT_README.md +0 -411
@@ -4,29 +4,59 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.installFromZip = installFromZip;
7
- const buffer_1 = require("buffer");
8
- const fflate_1 = require("fflate");
9
7
  const fs_1 = __importDefault(require("../native/fs"));
10
8
  const context_1 = require("../context");
11
9
  const image_manifest_1 = require("../image-manifest");
12
10
  const injectImageResolver_1 = require("../injectImageResolver");
13
11
  const fsUtils_1 = require("../fs/fsUtils");
12
+ const errors_1 = require("../errors");
14
13
  async function installFromZip(params) {
15
- const { zipArrayBuffer, hash, statusCb, platform = context_1.platform } = params;
16
- const zipBuffer = buffer_1.Buffer.from(zipArrayBuffer);
17
- let files;
14
+ const { downloadUrl, hash, statusCb, platform = context_1.platform } = params;
15
+ if (!hash) {
16
+ throw new Error('Missing bundle hash');
17
+ }
18
+ const bundleDir = `${context_1.BUNDLE_DROP_ROOT}/bundles/${hash}`;
19
+ await (0, fsUtils_1.ensureDir)(bundleDir);
20
+ const bundlePath = `${bundleDir}/main.jsbundle`;
21
+ const tempZipPath = `${context_1.BUNDLE_DROP_ROOT}/bundles/_tmp_${hash}.zip`;
22
+ let fileNames;
18
23
  try {
19
- files = (0, fflate_1.unzipSync)(new Uint8Array(zipBuffer));
24
+ try {
25
+ await fs_1.default.downloadFile(downloadUrl, tempZipPath);
26
+ }
27
+ catch (e) {
28
+ throw new errors_1.InstallPhaseError('download', e);
29
+ }
30
+ try {
31
+ fileNames = await fs_1.default.unzip(tempZipPath, bundleDir);
32
+ }
33
+ catch (e) {
34
+ throw new errors_1.InstallPhaseError('install', e);
35
+ }
36
+ if (!(await fs_1.default.exists(bundlePath))) {
37
+ throw new errors_1.InstallPhaseError('install', new Error('main.jsbundle missing after extraction'));
38
+ }
20
39
  }
21
40
  catch (e) {
22
- console.error('❌ unzipSync failed: Invalid ZIP data', e);
41
+ try {
42
+ await fs_1.default.unlink(bundleDir);
43
+ }
44
+ catch { /* best-effort cleanup */ }
23
45
  throw e;
24
46
  }
47
+ finally {
48
+ try {
49
+ await fs_1.default.unlink(tempZipPath);
50
+ }
51
+ catch { /* best-effort cleanup */ }
52
+ }
53
+ statusCb?.(`📁 ${fileNames.length} files extracted`);
54
+ // Read metadata from the extracted files
25
55
  const metadataFromZip = {};
26
56
  const metadataFile = platform === 'android' ? 'metadata-android.json' : 'metadata-ios.json';
27
- if (files[metadataFile]) {
57
+ if (fileNames.includes(metadataFile)) {
28
58
  try {
29
- const raw = buffer_1.Buffer.from(files[metadataFile]).toString();
59
+ const raw = await fs_1.default.readFile(`${bundleDir}/${metadataFile}`, 'utf8');
30
60
  const parsed = JSON.parse(raw);
31
61
  metadataFromZip.bundleVersion = parsed.bundleVersion ?? metadataFromZip.bundleVersion;
32
62
  metadataFromZip.version = parsed.version ?? metadataFromZip.version;
@@ -37,39 +67,16 @@ async function installFromZip(params) {
37
67
  console.warn('⚠️ Failed to parse bundle metadata from zip', e);
38
68
  }
39
69
  }
40
- const fileNames = Object.keys(files);
41
- statusCb?.(`📁 ${fileNames.length} files extracted from ZIP`);
42
- statusCb?.('💾 Writing files...');
43
- const resolvedHash = hash ?? metadataFromZip.hash;
44
- if (!resolvedHash) {
45
- throw new Error('Missing bundle hash');
46
- }
47
- // Build a runtime manifest from extracted assets to handle filename-only resolutions.
70
+ // Build runtime manifest from extracted filenames (assets only)
48
71
  const runtimeManifest = {};
49
- // Platform-specific bundle location (hash-scoped)
50
- const bundleDir = `${context_1.BUNDLE_DROP_ROOT}/bundles/${resolvedHash}`;
51
- await (0, fsUtils_1.ensureDir)(bundleDir);
52
- const bundlePath = `${bundleDir}/main.jsbundle`;
53
- for (const [filename, fileData] of Object.entries(files)) {
54
- const dataBuffer = buffer_1.Buffer.from(fileData);
55
- const base64 = dataBuffer.toString('base64');
56
- if (filename === 'main.jsbundle') {
57
- await (0, fsUtils_1.writeFileAtomicBase64)(bundlePath, base64);
58
- continue;
59
- }
60
- // Write other files under bundleDir (e.g., metadata, assets)
61
- const filePath = `${bundleDir}/${filename}`;
62
- await (0, fsUtils_1.ensureParentDir)(filePath);
63
- await fs_1.default.writeFile(filePath, base64, 'base64');
64
- // Collect runtime manifest entries for assets; support paths with or without "assets/" prefix.
72
+ for (const filename of fileNames) {
65
73
  if (filename.includes('drawable') || filename.startsWith('assets/') || filename.startsWith('res/')) {
66
74
  const noExt = filename.replace(/\.[^.]+$/, '');
67
75
  const base = noExt.split('/').pop();
68
76
  const withAssetsPrefix = filename.startsWith('assets/') ? filename : `assets/${filename}`;
69
- // Map to on-disk location relative to DocumentDirectoryPath
70
77
  const mappedPath = context_1.isIOS
71
- ? `${resolvedHash}/${filename}`
72
- : `bundle-drop/bundles/${resolvedHash}/${filename}`;
78
+ ? `${hash}/${filename}`
79
+ : `bundle-drop/bundles/${hash}/${filename}`;
73
80
  runtimeManifest[noExt.replace(/^assets\//, '')] = mappedPath;
74
81
  runtimeManifest[withAssetsPrefix.replace(/\.[^.]+$/, '')] = mappedPath;
75
82
  if (base && !runtimeManifest[base]) {
@@ -81,11 +88,11 @@ async function installFromZip(params) {
81
88
  }
82
89
  }
83
90
  }
84
- // ✅ Load image manifest (Android)
85
- if (platform === 'android' && files['image-manifest.json']) {
91
+ // Load image manifest (Android)
92
+ if (platform === 'android' && fileNames.includes('image-manifest.json')) {
86
93
  try {
87
- const manifest = buffer_1.Buffer.from(files['image-manifest.json']).toString();
88
- const parsed = JSON.parse(manifest);
94
+ const raw = await fs_1.default.readFile(`${bundleDir}/image-manifest.json`, 'utf8');
95
+ const parsed = JSON.parse(raw);
89
96
  Object.assign(image_manifest_1.imageManifest, parsed);
90
97
  statusCb?.(`🧩 Image manifest injected: ${Object.keys(parsed).length} items`);
91
98
  }
@@ -94,12 +101,10 @@ async function installFromZip(params) {
94
101
  statusCb?.('❌ Failed to parse image manifest');
95
102
  }
96
103
  }
97
- // Merge runtime manifest to catch any assets missing from the bundle-time manifest.
98
104
  if (platform === 'android' && Object.keys(runtimeManifest).length > 0) {
99
105
  Object.assign(image_manifest_1.imageManifest, runtimeManifest);
100
106
  }
101
107
  if (platform === 'android') {
102
- // Re-patch with the freshest manifest so newly downloaded assets resolve.
103
108
  (0, injectImageResolver_1.injectBundleDropImageResolver)(image_manifest_1.imageManifest);
104
109
  }
105
110
  return { bundlePath, metadataFromZip };
@@ -1,22 +1,41 @@
1
+ /**
2
+ * Shape of `bundle.drop.config.js` after it is loaded through Metro.
3
+ */
1
4
  export type BundleDropProjectConfig = {
5
+ /** BundleDrop backend base URL. */
2
6
  serverUrl: string;
7
+ /** Organization identity used for public API calls. */
3
8
  org: {
9
+ /** Organization slug. */
4
10
  slug: string;
5
11
  };
12
+ /** Project identity and public access configuration. */
6
13
  project: {
14
+ /** Human-readable project name. */
7
15
  name: string;
16
+ /** Project slug used by public API calls. */
8
17
  slug: string;
18
+ /** Optional public API key used by CLI/runtime integrations. */
9
19
  apiKey?: string;
10
20
  };
21
+ /** When true, route local dev traffic to emulator/simulator-friendly localhost URLs. */
11
22
  debugLocal?: boolean;
23
+ /** Native runtime versions for platform compatibility checks. */
12
24
  runtimeVersion?: {
25
+ /** iOS runtime version. */
13
26
  ios: string;
27
+ /** Android runtime version. */
14
28
  android: string;
15
29
  };
30
+ /** Default OTA channel used before runtime code sets another channel. */
16
31
  defaultChannel?: string;
32
+ /** Rollback/crash recovery tuning. */
17
33
  rollback?: {
34
+ /** Crash count required before rollback. */
18
35
  maxCrashCount?: number;
36
+ /** Time window, in seconds, used when counting startup crashes. */
19
37
  crashWindowSec?: number;
38
+ /** Time, in seconds, after which a candidate bundle is considered stable. */
20
39
  commitTimeoutSec?: number;
21
40
  };
22
41
  };
package/lib/loadConfig.js CHANGED
@@ -20,12 +20,16 @@ function loadConfig() {
20
20
  return cfg;
21
21
  }
22
22
  catch (e) {
23
- console.log('[BundleDrop] loadConfig failed:', e);
24
- return {
25
- serverUrl: 'http://localhost:4000',
26
- org: { slug: 'default-org' },
27
- project: { name: 'BundleDrop', slug: 'default' },
28
- debugLocal: true,
29
- };
23
+ if (typeof __DEV__ !== 'undefined' && __DEV__) {
24
+ console.warn('[BundleDrop] loadConfig failed, using dev defaults:', e);
25
+ return {
26
+ serverUrl: 'https://api.bundledrop.app',
27
+ org: { slug: 'default-org' },
28
+ project: { name: 'BundleDrop', slug: 'default' },
29
+ debugLocal: false,
30
+ };
31
+ }
32
+ throw new Error('[BundleDrop] bundle.drop.config.js could not be loaded. ' +
33
+ 'Ensure the config file exists and Metro is configured with the bundle-drop-config alias.');
30
34
  }
31
35
  }
@@ -1,10 +1,6 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.installBundle = exports.downloadUpdate = void 0;
7
- const axios_cjs_1 = __importDefault(require("axios/dist/browser/axios.cjs"));
8
4
  const context_1 = require("../context");
9
5
  const bundleInfo_1 = require("../bundleInfo");
10
6
  const bundlePointer_1 = require("../fs/bundlePointer");
@@ -67,40 +63,26 @@ async function downloadAndStageUpdate(options, onStatusUpdate) {
67
63
  },
68
64
  });
69
65
  }
70
- // Fetch bundle zip from server.
71
66
  statusCb?.('⬇️ Downloading full bundle ZIP!...');
72
- let zipResponse;
73
- try {
74
- zipResponse = await axios_cjs_1.default.get(bundleZipUrl, {
75
- responseType: 'arraybuffer',
76
- });
77
- }
78
- catch (e) {
79
- throw new errors_1.BundleDropError({
80
- message: 'Failed to download update ZIP',
81
- code: 'DOWNLOAD_FAILED',
82
- step: 'download',
83
- context: { channelName, platform, url: bundleZipUrl },
84
- cause: e,
85
- });
86
- }
87
67
  const hash = serverHash;
88
68
  let installResult;
89
69
  try {
90
70
  installResult = await (0, installFromZip_1.installFromZip)({
91
- zipArrayBuffer: zipResponse.data,
71
+ downloadUrl: bundleZipUrl,
92
72
  hash,
93
73
  platform,
94
74
  statusCb,
95
75
  });
96
76
  }
97
77
  catch (e) {
78
+ const phaseErr = (0, errors_1.isInstallPhaseError)(e);
79
+ const isDownload = phaseErr && e.phase === 'download';
98
80
  throw new errors_1.BundleDropError({
99
- message: 'Failed to install update ZIP',
100
- code: 'INSTALL_FAILED',
101
- step: 'install',
81
+ message: isDownload ? 'Failed to download update ZIP' : 'Failed to install update ZIP',
82
+ code: isDownload ? 'DOWNLOAD_FAILED' : 'INSTALL_FAILED',
83
+ step: isDownload ? 'download' : 'install',
102
84
  context: { channelName, platform, hash },
103
- cause: e,
85
+ cause: phaseErr ? e.originalCause : e,
104
86
  });
105
87
  }
106
88
  const { bundlePath, metadataFromZip } = installResult;
@@ -33,13 +33,13 @@ async function reportInstalledIfReady(state) {
33
33
  (0, installId_1.getOrCreateInstallId)(),
34
34
  (0, userProperties_1.getCurrentUserProperties)(),
35
35
  ]);
36
- const environment = (0, initState_1.getBundleDropRuntimeConfig)()?.environment ?? null;
36
+ const appEnvironment = (0, initState_1.getBundleDropRuntimeConfig)()?.environment ?? null;
37
37
  await (0, clientApi_1.reportInstalled)(context_1.config.project.slug, info.hash, {
38
38
  channelName: info.channelName,
39
39
  platform: info.platform,
40
40
  installId,
41
41
  runtimeVersion: info.runtimeVersion ?? context_1.runtimeVersion ?? null,
42
- environment,
42
+ environment: appEnvironment,
43
43
  userProperties: Object.keys(userProperties).length > 0 ? userProperties : undefined,
44
44
  });
45
45
  await (0, bundleInfo_1.updateBundleInfo)({ lastInstalledReportedHash: info.hash });
@@ -20,21 +20,21 @@ export declare function markCandidateActivated(hash: string): Promise<void>;
20
20
  export declare function commitActiveBundle(cached?: {
21
21
  currentPointer?: BundlePointer | null;
22
22
  }): Promise<void>;
23
- export declare function evaluateRollbackOnLaunch(policy?: RollbackPolicy, cached?: {
23
+ export declare function evaluateRollbackOnLaunch(policy: Required<RollbackPolicy>, cached?: {
24
24
  currentPointer?: BundlePointer | null;
25
25
  rollbackState?: RollbackState | null;
26
26
  }): Promise<{
27
27
  shouldRollback: boolean;
28
28
  reason?: 'crash_loop' | 'commit_timeout';
29
29
  }>;
30
- export declare function rollbackToPreviousIfNeeded(policy?: RollbackPolicy, cached?: {
30
+ export declare function rollbackToPreviousIfNeeded(policy: Required<RollbackPolicy>, cached?: {
31
31
  currentPointer?: BundlePointer | null;
32
32
  rollbackState?: RollbackState | null;
33
33
  }): Promise<{
34
34
  rolledBack: boolean;
35
35
  reason?: 'crash_loop' | 'commit_timeout';
36
36
  }>;
37
- export declare function getRollbackPolicy(): RollbackPolicy | undefined;
37
+ export declare function getRollbackPolicy(): Required<RollbackPolicy>;
38
38
  export declare function rollbackToPreviousOrNative(): Promise<{
39
39
  rolledBack: boolean;
40
40
  toNative?: boolean;
@@ -16,21 +16,9 @@ const fsUtils_1 = require("../fs/fsUtils");
16
16
  const bundlePointer_1 = require("../fs/bundlePointer");
17
17
  const bundleInfo_1 = require("../bundleInfo");
18
18
  const STATE_PATH = `${context_1.BUNDLE_DROP_ROOT}/state.json`;
19
- const DEFAULT_POLICY = {
20
- maxCrashCount: 2,
21
- crashWindowSec: 300,
22
- commitTimeoutSec: 300,
23
- };
24
19
  function nowSec() {
25
20
  return Math.floor(Date.now() / 1000);
26
21
  }
27
- function normalizePolicy(policy) {
28
- return {
29
- maxCrashCount: policy?.maxCrashCount ?? DEFAULT_POLICY.maxCrashCount,
30
- crashWindowSec: policy?.crashWindowSec ?? DEFAULT_POLICY.crashWindowSec,
31
- commitTimeoutSec: policy?.commitTimeoutSec ?? DEFAULT_POLICY.commitTimeoutSec,
32
- };
33
- }
34
22
  async function readState() {
35
23
  try {
36
24
  if (!(await fs_1.default.exists(STATE_PATH)))
@@ -88,7 +76,6 @@ async function evaluateRollbackOnLaunch(policy, cached) {
88
76
  return { shouldRollback: false };
89
77
  const now = nowSec();
90
78
  const state = (cached?.rollbackState !== undefined ? cached.rollbackState : await readState()) || {};
91
- const normalized = normalizePolicy(policy);
92
79
  const next = {
93
80
  ...state,
94
81
  activeHash,
@@ -97,18 +84,18 @@ async function evaluateRollbackOnLaunch(policy, cached) {
97
84
  const isCandidate = state.candidateHash === activeHash && state.candidateCommitted !== true;
98
85
  if (isCandidate) {
99
86
  const windowStart = state.crashWindowStartedAt ?? now;
100
- const inWindow = now - windowStart <= normalized.crashWindowSec;
87
+ const inWindow = now - windowStart <= policy.crashWindowSec;
101
88
  const crashCount = inWindow ? (state.crashCount ?? 0) + 1 : 1;
102
89
  next.crashCount = crashCount;
103
90
  next.crashWindowStartedAt = inWindow ? windowStart : now;
104
- if (normalized.maxCrashCount > 0 &&
105
- crashCount >= normalized.maxCrashCount) {
91
+ if (policy.maxCrashCount > 0 &&
92
+ crashCount >= policy.maxCrashCount) {
106
93
  await writeState(next);
107
94
  return { shouldRollback: true, reason: 'crash_loop' };
108
95
  }
109
- if (normalized.commitTimeoutSec > 0 &&
96
+ if (policy.commitTimeoutSec > 0 &&
110
97
  state.candidateActivatedAt &&
111
- now - state.candidateActivatedAt > normalized.commitTimeoutSec) {
98
+ now - state.candidateActivatedAt > policy.commitTimeoutSec) {
112
99
  await writeState(next);
113
100
  return { shouldRollback: true, reason: 'commit_timeout' };
114
101
  }
@@ -124,7 +111,7 @@ async function rollbackToPreviousIfNeeded(policy, cached) {
124
111
  return res.rolledBack ? { rolledBack: true, reason: decision.reason } : { rolledBack: false };
125
112
  }
126
113
  function getRollbackPolicy() {
127
- return context_1.config.rollback;
114
+ return context_1.bundleDropConfig.rollback;
128
115
  }
129
116
  async function rollbackToPreviousOrNative() {
130
117
  const previous = await (0, bundlePointer_1.rollbackToPreviousPointer)();
@@ -47,12 +47,12 @@ async function checkForUpdate(channelName = context_2.defaultChannel, onStatusUp
47
47
  ]);
48
48
  const currentHash = currentPtr?.hash ?? local?.hash ?? null;
49
49
  const previousHash = previousPtr?.hash ?? null;
50
- const environment = (0, initState_1.getBundleDropRuntimeConfig)()?.environment ?? null;
50
+ const appEnvironment = (0, initState_1.getBundleDropRuntimeConfig)()?.environment ?? null;
51
51
  const res = await (0, clientApi_1.postOtaResolve)(project.slug, {
52
52
  channelName,
53
53
  platform: context_1.platform,
54
54
  runtimeVersion: context_1.runtimeVersion ?? null,
55
- environment,
55
+ environment: appEnvironment,
56
56
  currentHash,
57
57
  currentUserProperties,
58
58
  previousHash,
@@ -2,8 +2,11 @@ declare function exists(path: string): Promise<boolean>;
2
2
  declare function readFile(path: string, encoding?: 'utf8' | 'base64'): Promise<string>;
3
3
  declare function writeFile(path: string, content: string, encoding?: 'utf8' | 'base64'): Promise<void>;
4
4
  declare function mkdir(path: string): Promise<void>;
5
+ declare function readDir(path: string): Promise<string[]>;
5
6
  declare function unlink(path: string): Promise<void>;
6
7
  declare function moveFile(src: string, dest: string): Promise<void>;
8
+ declare function unzip(zipPath: string, destPath: string): Promise<string[]>;
9
+ declare function downloadFile(url: string, destPath: string): Promise<void>;
7
10
  declare const BundleDropFS: {
8
11
  DocumentDirectoryPath: string;
9
12
  LibraryDirectoryPath: string;
@@ -11,7 +14,10 @@ declare const BundleDropFS: {
11
14
  readFile: typeof readFile;
12
15
  writeFile: typeof writeFile;
13
16
  mkdir: typeof mkdir;
17
+ readDir: typeof readDir;
14
18
  unlink: typeof unlink;
15
19
  moveFile: typeof moveFile;
20
+ unzip: typeof unzip;
21
+ downloadFile: typeof downloadFile;
16
22
  };
17
23
  export default BundleDropFS;
package/lib/native/fs.js CHANGED
@@ -2,24 +2,48 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const react_native_1 = require("react-native");
4
4
  const { BundleDrop } = react_native_1.NativeModules;
5
+ function assertModule() {
6
+ if (!BundleDrop) {
7
+ throw new Error('BundleDrop native module is not linked. ' +
8
+ 'Run pod install (iOS) or rebuild (Android).');
9
+ }
10
+ }
5
11
  async function exists(path) {
12
+ assertModule();
6
13
  return BundleDrop.fsExists(path);
7
14
  }
8
15
  async function readFile(path, encoding = 'utf8') {
16
+ assertModule();
9
17
  return BundleDrop.fsReadFile(path, encoding);
10
18
  }
11
19
  async function writeFile(path, content, encoding = 'utf8') {
20
+ assertModule();
12
21
  return BundleDrop.fsWriteFile(path, content, encoding);
13
22
  }
14
23
  async function mkdir(path) {
24
+ assertModule();
15
25
  return BundleDrop.fsMkdir(path);
16
26
  }
27
+ async function readDir(path) {
28
+ assertModule();
29
+ return BundleDrop.fsReadDir(path);
30
+ }
17
31
  async function unlink(path) {
32
+ assertModule();
18
33
  return BundleDrop.fsUnlink(path);
19
34
  }
20
35
  async function moveFile(src, dest) {
36
+ assertModule();
21
37
  return BundleDrop.fsMoveFile(src, dest);
22
38
  }
39
+ async function unzip(zipPath, destPath) {
40
+ assertModule();
41
+ return BundleDrop.fsUnzip(zipPath, destPath);
42
+ }
43
+ async function downloadFile(url, destPath) {
44
+ assertModule();
45
+ return BundleDrop.fsDownloadFile(url, destPath);
46
+ }
23
47
  const BundleDropFS = {
24
48
  DocumentDirectoryPath: (BundleDrop?.DocumentDirectoryPath ?? ''),
25
49
  LibraryDirectoryPath: (BundleDrop?.LibraryDirectoryPath ?? ''),
@@ -27,7 +51,10 @@ const BundleDropFS = {
27
51
  readFile,
28
52
  writeFile,
29
53
  mkdir,
54
+ readDir,
30
55
  unlink,
31
56
  moveFile,
57
+ unzip,
58
+ downloadFile,
32
59
  };
33
60
  exports.default = BundleDropFS;
@@ -5,7 +5,7 @@ export declare const BUNDLE_DROP_DISABLED_MESSAGE = "BundleDrop is disabled. OTA
5
5
  * Runtime options for `BundleDrop.init(...)`.
6
6
  */
7
7
  export type BundleDropInitOptions = {
8
- /** Deployment environment shown in analytics, for example `production`, `staging`, or `development`. */
8
+ /** Customer app environment shown in analytics, for example `production`, `staging`, or `development`. */
9
9
  environment: string;
10
10
  /** Defaults to `true`. Set to `false` to keep BundleDrop configured but fully no-op for the current app process. */
11
11
  enabled?: boolean;
@@ -22,7 +22,7 @@ export type BundleDropInitOptions = {
22
22
  * Resolved runtime configuration currently active inside the singleton service.
23
23
  */
24
24
  export type BundleDropRuntimeConfig = {
25
- /** Deployment environment sent to BundleDrop analytics and resolve payloads. */
25
+ /** Customer app environment sent to BundleDrop analytics and resolve payloads. */
26
26
  environment: string;
27
27
  /** Whether BundleDrop is active or running in disabled no-op mode. */
28
28
  enabled: boolean;
@@ -24,6 +24,7 @@ exports.resetBundleDropRuntimeServiceForTests = resetBundleDropRuntimeServiceFor
24
24
  exports.waitForBundleDropStartupForTests = waitForBundleDropStartupForTests;
25
25
  const bundleInfo_1 = require("../bundleInfo");
26
26
  const context_1 = require("../context");
27
+ const fsUtils_1 = require("../fs/fsUtils");
27
28
  const bundleDropNative_1 = require("../native/bundleDropNative");
28
29
  const bundlePointer_1 = require("../fs/bundlePointer");
29
30
  const downloadAndInstall_1 = require("../manager/downloadAndInstall");
@@ -168,6 +169,7 @@ async function waitForStartupIfNeeded() {
168
169
  async function runStartupFlow() {
169
170
  const runtime = (0, initState_1.assertBundleDropInitialized)();
170
171
  const statusCb = status => emitStatus(status);
172
+ void (0, fsUtils_1.cleanOrphanedTempZips)(`${context_1.BUNDLE_DROP_ROOT}/bundles`);
171
173
  const [bundleInfo, bundlePath, currentPointer, rollbackState] = await Promise.all([
172
174
  (0, bundleInfo_1.readBundleInfo)(),
173
175
  (0, bundleDropNative_1.getDownloadedBundlePathNative)(),
@@ -103,8 +103,8 @@ function runBundleScript(options) {
103
103
  --platform ${platform} \
104
104
  --dev false \
105
105
  --entry-file index.js \
106
- --bundle-output ${bundlePath} \
107
- --assets-dest ${assetsDir}`, { stdio: 'inherit' });
106
+ --bundle-output "${bundlePath}" \
107
+ --assets-dest "${assetsDir}"`, { stdio: 'inherit' });
108
108
  console.log('✅ Bundle created:', bundlePath);
109
109
  const osBin = process.platform === 'darwin'
110
110
  ? 'osx-bin'
@@ -0,0 +1,2 @@
1
+ export declare function resolveXcodeBuildSetting(projectRoot: string, variableName: string): string | null;
2
+ export declare function resolveIosPlistVersion(rawVersion: string, projectRoot: string): string | null;
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.resolveXcodeBuildSetting = resolveXcodeBuildSetting;
37
+ exports.resolveIosPlistVersion = resolveIosPlistVersion;
38
+ const fs = __importStar(require("fs"));
39
+ const path = __importStar(require("path"));
40
+ const XCODE_VAR_RE = /\$\(([^)]+)\)/;
41
+ function resolveXcodeBuildSetting(projectRoot, variableName) {
42
+ const iosDir = path.join(projectRoot, 'ios');
43
+ if (!fs.existsSync(iosDir))
44
+ return null;
45
+ const xcodeproj = fs.readdirSync(iosDir).find(f => f.endsWith('.xcodeproj'));
46
+ if (!xcodeproj)
47
+ return null;
48
+ const pbxprojPath = path.join(iosDir, xcodeproj, 'project.pbxproj');
49
+ if (!fs.existsSync(pbxprojPath))
50
+ return null;
51
+ const content = fs.readFileSync(pbxprojPath, 'utf-8');
52
+ const pattern = new RegExp(`${variableName}\\s*=\\s*([^;]+);`);
53
+ const match = content.match(pattern);
54
+ if (!match)
55
+ return null;
56
+ const value = match[1].trim().replace(/^["']|["']$/g, '');
57
+ if (!value || XCODE_VAR_RE.test(value))
58
+ return null;
59
+ return value;
60
+ }
61
+ function resolveIosPlistVersion(rawVersion, projectRoot) {
62
+ const xcodeVarMatch = rawVersion.match(XCODE_VAR_RE);
63
+ if (!xcodeVarMatch)
64
+ return rawVersion;
65
+ const variableName = xcodeVarMatch[1];
66
+ const resolved = resolveXcodeBuildSetting(projectRoot, variableName);
67
+ if (resolved) {
68
+ console.warn(`⚠️ Info.plist contains $(${variableName}); resolved to "${resolved}" from .pbxproj`);
69
+ return resolved;
70
+ }
71
+ console.error(`❌ Info.plist contains $(${variableName}) which could not be resolved.\n` +
72
+ ` Pass --version=x.y.z explicitly, or ensure MARKETING_VERSION is set in your .pbxproj.`);
73
+ return null;
74
+ }
@@ -48,6 +48,7 @@ const fs = __importStar(require("fs"));
48
48
  const os_1 = __importDefault(require("os"));
49
49
  const path = __importStar(require("path"));
50
50
  const plist = __importStar(require("plist"));
51
+ const resolve_ios_version_1 = require("./resolve-ios-version");
51
52
  const getPackageRoot = () => process.env.BUNDLE_DROP_PACKAGE_ROOT_OVERRIDE || path.resolve(__dirname, '..', '..');
52
53
  function findProjectRoot(startDir) {
53
54
  let dir = path.resolve(startDir);
@@ -192,11 +193,16 @@ async function runUploadBundle(options) {
192
193
  try {
193
194
  const plistContent = fs.readFileSync(plistFile, 'utf-8');
194
195
  const parsed = plist.parse(plistContent);
195
- version = parsed.CFBundleShortVersionString;
196
- if (!version) {
196
+ const rawVersion = parsed.CFBundleShortVersionString;
197
+ if (!rawVersion) {
197
198
  console.error('❌ Could not find CFBundleShortVersionString in plist');
198
199
  process.exit(1);
199
200
  }
201
+ const resolved = (0, resolve_ios_version_1.resolveIosPlistVersion)(rawVersion, projectRoot);
202
+ if (!resolved) {
203
+ process.exit(1);
204
+ }
205
+ version = resolved;
200
206
  }
201
207
  catch (err) {
202
208
  console.error('❌ Failed to read plist file:', err);
@@ -224,8 +230,8 @@ async function runUploadBundle(options) {
224
230
  const compiledBundleScript = path.join(packageRoot, 'lib', 'scripts', 'bundle.js');
225
231
  const tsBundleScript = path.join(packageRoot, 'src', 'scripts', 'bundle.ts');
226
232
  const bundleCommand = fs.existsSync(compiledBundleScript)
227
- ? `node ${compiledBundleScript}`
228
- : `ts-node ${tsBundleScript}`;
233
+ ? `node "${compiledBundleScript}"`
234
+ : `ts-node "${tsBundleScript}"`;
229
235
  try {
230
236
  console.log(`📦 Running bundler for ${platform}...`);
231
237
  (0, child_process_1.execSync)(`${bundleCommand} ${platform}`, {
package/lib/types.d.ts CHANGED
@@ -1 +1,4 @@
1
+ /**
2
+ * Startup policy controlling what BundleDrop does after local state hydration.
3
+ */
1
4
  export type UpdatePolicy = 'manual' | 'immediate' | 'on-next-launch';