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

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 (63) hide show
  1. package/android/build.gradle +2 -0
  2. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +12 -48
  3. package/android/src/main/java/com/bundledrop/BundleDropNativePaths.kt +64 -0
  4. package/android/src/main/java/com/bundledrop/BundleDropOtaPrefs.kt +41 -0
  5. package/ios/BundleDropBridge.m +4 -0
  6. package/ios/BundleDropLocator.h +11 -0
  7. package/ios/BundleDropLocator.swift +11 -1
  8. package/ios/BundleDropModule.swift +10 -0
  9. package/lib/CLI/cli.js +56 -6
  10. package/lib/CLI/scripts/aipowered/apply-plan.d.ts +10 -0
  11. package/lib/CLI/scripts/aipowered/apply-plan.js +50 -0
  12. package/lib/CLI/scripts/aipowered/backend-client.d.ts +6 -0
  13. package/lib/CLI/scripts/aipowered/backend-client.js +34 -0
  14. package/lib/CLI/scripts/aipowered/diff-preview.d.ts +7 -0
  15. package/lib/CLI/scripts/aipowered/diff-preview.js +33 -0
  16. package/lib/CLI/scripts/aipowered/init-native-config.d.ts +2 -0
  17. package/lib/CLI/scripts/aipowered/init-native-config.js +131 -0
  18. package/lib/CLI/scripts/aipowered/scanner.d.ts +5 -0
  19. package/lib/CLI/scripts/aipowered/scanner.js +349 -0
  20. package/lib/CLI/scripts/aipowered/types.d.ts +53 -0
  21. package/lib/CLI/scripts/aipowered/types.js +2 -0
  22. package/lib/CLI/scripts/aipowered/validate-plan.d.ts +8 -0
  23. package/lib/CLI/scripts/aipowered/validate-plan.js +164 -0
  24. package/lib/CLI/scripts/init-config.js +10 -5
  25. package/lib/CLI/scripts/init-native-config.js +1 -1
  26. package/lib/CLI/scripts/post-init.js +7 -18
  27. package/lib/CLI/scripts/upload-cli.d.ts +2 -0
  28. package/lib/CLI/scripts/upload-cli.js +53 -25
  29. package/lib/CLI/utils/ui.d.ts +3 -0
  30. package/lib/CLI/utils/ui.js +26 -0
  31. package/lib/api/clientApi.d.ts +2 -1
  32. package/lib/api/clientApi.js +9 -0
  33. package/lib/api/types.d.ts +17 -0
  34. package/lib/context.d.ts +4 -4
  35. package/lib/context.js +2 -2
  36. package/lib/fs/bundlePointer.d.ts +2 -0
  37. package/lib/fs/bundlePointer.js +14 -4
  38. package/lib/index.d.ts +6 -3
  39. package/lib/index.js +5 -1
  40. package/lib/injectImageResolver.js +6 -15
  41. package/lib/loadConfig.d.ts +4 -4
  42. package/lib/manager/downloadAndInstall.d.ts +3 -0
  43. package/lib/manager/downloadAndInstall.js +23 -3
  44. package/lib/manager/reporting.d.ts +2 -0
  45. package/lib/manager/reporting.js +25 -0
  46. package/lib/manager/rollbackState.d.ts +25 -8
  47. package/lib/manager/rollbackState.js +87 -22
  48. package/lib/manager/updateCheck.js +15 -1
  49. package/lib/manager/updateState.d.ts +5 -1
  50. package/lib/manager/updateState.js +20 -11
  51. package/lib/native/bundleDropNative.d.ts +1 -0
  52. package/lib/native/bundleDropNative.js +14 -0
  53. package/lib/runtime/service.d.ts +28 -0
  54. package/lib/runtime/service.js +175 -16
  55. package/lib/scripts/bundle.d.ts +4 -1
  56. package/lib/scripts/bundle.js +41 -28
  57. package/lib/scripts/projectRoot.d.ts +1 -0
  58. package/lib/scripts/projectRoot.js +54 -0
  59. package/lib/scripts/upload-bundle.d.ts +2 -1
  60. package/lib/scripts/upload-bundle.js +46 -37
  61. package/lib/useBundleDrop.d.ts +2 -0
  62. package/lib/useBundleDrop.js +1 -0
  63. package/package.json +3 -2
@@ -0,0 +1,349 @@
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.isTrustedAiPlanningServer = exports.isSummaryOnlyAiContextFile = void 0;
7
+ exports.findProjectRoot = findProjectRoot;
8
+ exports.scanProjectForAiNativeInit = scanProjectForAiNativeInit;
9
+ const crypto_1 = __importDefault(require("crypto"));
10
+ const fs_extra_1 = __importDefault(require("fs-extra"));
11
+ const module_1 = require("module");
12
+ const os_1 = __importDefault(require("os"));
13
+ const path_1 = __importDefault(require("path"));
14
+ const MAX_UP = 12;
15
+ const MAX_FILE_BYTES = 80 * 1024;
16
+ const MAX_TOTAL_BYTES = 350 * 1024;
17
+ const PRODUCTION_AI_HOST = 'api.bundledrop.app';
18
+ const LOCAL_AI_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]', '10.0.2.2']);
19
+ const SKIP_DIRS = new Set([
20
+ 'node_modules',
21
+ 'build',
22
+ 'Pods',
23
+ '.gradle',
24
+ 'DerivedData',
25
+ '.git',
26
+ 'lib',
27
+ 'dist',
28
+ ]);
29
+ const sha256 = (content) => crypto_1.default.createHash('sha256').update(content).digest('hex');
30
+ const toPosix = (filePath) => filePath.split(path_1.default.sep).join('/');
31
+ const normalizeServerUrl = (url) => url.replace(/\/+$/, '');
32
+ const readJsonFile = (filePath) => JSON.parse(fs_extra_1.default.readFileSync(filePath, 'utf8'));
33
+ const CONTEXT_SUMMARY_SIGNALS = [
34
+ 'react-native',
35
+ '@gfean/react-native-bundle-drop',
36
+ 'react-native-bundle-drop',
37
+ 'bundle-drop-config',
38
+ 'serverUrl',
39
+ 'org',
40
+ 'project',
41
+ 'getDefaultConfig',
42
+ 'mergeConfig',
43
+ 'com.android.application',
44
+ 'com.facebook.react',
45
+ 'react-native-gradle-plugin',
46
+ 'pluginManagement',
47
+ 'includeBuild',
48
+ 'newArchEnabled',
49
+ 'hermesEnabled',
50
+ 'use_react_native!',
51
+ 'use_native_modules!',
52
+ ];
53
+ const isSummaryOnlyAiContextFile = (relativePath) => relativePath === 'bundle.drop.config.js' ||
54
+ relativePath === 'metro.config.js' ||
55
+ relativePath.endsWith('.gradle') ||
56
+ relativePath.endsWith('.gradle.kts') ||
57
+ relativePath.endsWith('settings.gradle') ||
58
+ relativePath.endsWith('settings.gradle.kts') ||
59
+ relativePath.endsWith('Podfile') ||
60
+ relativePath === 'package.json';
61
+ exports.isSummaryOnlyAiContextFile = isSummaryOnlyAiContextFile;
62
+ const summarizeContextContent = (relativePath, rawContent, sizeBytes) => {
63
+ const matchedSignals = CONTEXT_SUMMARY_SIGNALS.filter(signal => rawContent.includes(signal));
64
+ const signalLines = matchedSignals.length
65
+ ? matchedSignals.map(signal => `- ${signal}`).join('\n')
66
+ : '- none detected';
67
+ return [
68
+ `BundleDrop context summary for ${relativePath}`,
69
+ 'Full content omitted to reduce AI planning tokens; this context file is not patchable by init-native.',
70
+ `sizeBytes: ${sizeBytes}`,
71
+ 'signals:',
72
+ signalLines,
73
+ '',
74
+ ].join('\n');
75
+ };
76
+ const codeLikeContent = (content) => {
77
+ let result = '';
78
+ let state = 'code';
79
+ for (let i = 0; i < content.length; i++) {
80
+ const char = content[i];
81
+ const next = content[i + 1];
82
+ if (state === 'line-comment') {
83
+ if (char === '\n') {
84
+ state = 'code';
85
+ result += char;
86
+ }
87
+ continue;
88
+ }
89
+ if (state === 'block-comment') {
90
+ if (char === '*' && next === '/') {
91
+ state = 'code';
92
+ i++;
93
+ }
94
+ continue;
95
+ }
96
+ if (state === 'single' || state === 'double' || state === 'template') {
97
+ if (char === '\\') {
98
+ i++;
99
+ continue;
100
+ }
101
+ if ((state === 'single' && char === "'") ||
102
+ (state === 'double' && char === '"') ||
103
+ (state === 'template' && char === '`')) {
104
+ state = 'code';
105
+ }
106
+ continue;
107
+ }
108
+ if (char === '/' && next === '/') {
109
+ state = 'line-comment';
110
+ i++;
111
+ continue;
112
+ }
113
+ if (char === '/' && next === '*') {
114
+ state = 'block-comment';
115
+ i++;
116
+ continue;
117
+ }
118
+ if (char === "'") {
119
+ state = 'single';
120
+ continue;
121
+ }
122
+ if (char === '"') {
123
+ state = 'double';
124
+ continue;
125
+ }
126
+ if (char === '`') {
127
+ state = 'template';
128
+ continue;
129
+ }
130
+ result += char;
131
+ }
132
+ return result;
133
+ };
134
+ const hasBundleDropResolverCall = (content) => {
135
+ const code = codeLikeContent(content);
136
+ return (code.includes('BundleDropModule.resolveJSBundleFile') ||
137
+ code.includes('BundleDropLocator.bundleURL()') ||
138
+ code.includes('[BundleDropLocator bundleURL]'));
139
+ };
140
+ const isTrustedAiPlanningServer = (serverUrl) => {
141
+ if (process.env.BUNDLE_DROP_ALLOW_UNTRUSTED_AI_SERVER === '1')
142
+ return true;
143
+ try {
144
+ const parsed = new URL(serverUrl);
145
+ if (parsed.hostname === PRODUCTION_AI_HOST)
146
+ return parsed.protocol === 'https:';
147
+ if (LOCAL_AI_HOSTS.has(parsed.hostname)) {
148
+ return parsed.protocol === 'http:' || parsed.protocol === 'https:';
149
+ }
150
+ }
151
+ catch {
152
+ return false;
153
+ }
154
+ return false;
155
+ };
156
+ exports.isTrustedAiPlanningServer = isTrustedAiPlanningServer;
157
+ const loadBundleDropConfig = (configPath) => {
158
+ const moduleLike = { exports: {} };
159
+ const content = fs_extra_1.default.readFileSync(configPath, 'utf8');
160
+ const localRequire = (0, module_1.createRequire)(configPath);
161
+ const load = new Function('module', 'exports', 'require', '__dirname', '__filename', content);
162
+ load(moduleLike, moduleLike.exports, localRequire, path_1.default.dirname(configPath), configPath);
163
+ return moduleLike.exports;
164
+ };
165
+ function findProjectRoot(startDir = process.cwd()) {
166
+ let dir = path_1.default.resolve(startDir);
167
+ for (let i = 0; i < MAX_UP; i++) {
168
+ if (fs_extra_1.default.existsSync(path_1.default.join(dir, 'bundle.drop.config.js')))
169
+ return dir;
170
+ const parent = path_1.default.dirname(dir);
171
+ if (parent === dir)
172
+ break;
173
+ dir = parent;
174
+ }
175
+ return path_1.default.resolve(startDir);
176
+ }
177
+ const findFilesByName = (root, names) => {
178
+ if (!fs_extra_1.default.existsSync(root))
179
+ return [];
180
+ const matches = [];
181
+ const stack = [root];
182
+ while (stack.length) {
183
+ const current = stack.pop();
184
+ const stat = fs_extra_1.default.lstatSync(current);
185
+ if (stat.isSymbolicLink())
186
+ continue;
187
+ if (stat.isDirectory()) {
188
+ if (SKIP_DIRS.has(path_1.default.basename(current)))
189
+ continue;
190
+ for (const entry of fs_extra_1.default.readdirSync(current)) {
191
+ stack.push(path_1.default.join(current, entry));
192
+ }
193
+ }
194
+ else if (stat.isFile() && names.has(path_1.default.basename(current))) {
195
+ matches.push(current);
196
+ }
197
+ }
198
+ return matches.sort();
199
+ };
200
+ const maybeAddFile = (files, seen, projectRoot, filePath, totalBytes) => {
201
+ if (!fs_extra_1.default.existsSync(filePath))
202
+ return;
203
+ const stat = fs_extra_1.default.lstatSync(filePath);
204
+ if (stat.isSymbolicLink() || !stat.isFile())
205
+ return;
206
+ const relative = toPosix(path_1.default.relative(projectRoot, filePath));
207
+ /* istanbul ignore next -- defensive guard in case discovery returns the same path twice */
208
+ if (seen.has(relative))
209
+ return;
210
+ const bytes = stat.size;
211
+ const rawContent = fs_extra_1.default.readFileSync(filePath, 'utf8');
212
+ const content = (0, exports.isSummaryOnlyAiContextFile)(relative)
213
+ ? summarizeContextContent(relative, rawContent, bytes)
214
+ : rawContent;
215
+ const contentBytes = Buffer.byteLength(content, 'utf8');
216
+ if (contentBytes > MAX_FILE_BYTES || totalBytes.value + contentBytes > MAX_TOTAL_BYTES)
217
+ return;
218
+ totalBytes.value += contentBytes;
219
+ seen.add(relative);
220
+ files.push({ path: relative, content, sha256: sha256(content) });
221
+ };
222
+ const collectFiles = (projectRoot) => {
223
+ const files = [];
224
+ const seen = new Set();
225
+ const totalBytes = { value: 0 };
226
+ const add = (relativePath) => maybeAddFile(files, seen, projectRoot, path_1.default.join(projectRoot, relativePath), totalBytes);
227
+ add('package.json');
228
+ add('bundle.drop.config.js');
229
+ add('metro.config.js');
230
+ add('android/build.gradle');
231
+ add('android/build.gradle.kts');
232
+ add('android/settings.gradle');
233
+ add('android/settings.gradle.kts');
234
+ add('android/app/build.gradle');
235
+ add('android/app/build.gradle.kts');
236
+ add('ios/Podfile');
237
+ for (const srcDir of ['java', 'kotlin']) {
238
+ for (const filePath of findFilesByName(path_1.default.join(projectRoot, 'android', 'app', 'src', 'main', srcDir), new Set(['MainApplication.kt', 'MainApplication.java']))) {
239
+ maybeAddFile(files, seen, projectRoot, filePath, totalBytes);
240
+ }
241
+ }
242
+ for (const filePath of findFilesByName(path_1.default.join(projectRoot, 'ios'), new Set(['AppDelegate.swift', 'AppDelegate.mm', 'AppDelegate.m']))) {
243
+ maybeAddFile(files, seen, projectRoot, filePath, totalBytes);
244
+ }
245
+ return files;
246
+ };
247
+ const detectRnVersion = (projectRoot) => {
248
+ const packagePath = path_1.default.join(projectRoot, 'package.json');
249
+ if (!fs_extra_1.default.existsSync(packagePath))
250
+ return null;
251
+ try {
252
+ const pkg = readJsonFile(packagePath);
253
+ return (pkg.dependencies?.['react-native'] ||
254
+ pkg.devDependencies?.['react-native'] ||
255
+ pkg.peerDependencies?.['react-native'] ||
256
+ null);
257
+ }
258
+ catch {
259
+ return null;
260
+ }
261
+ };
262
+ const detectSignals = (files) => {
263
+ const allContent = files.map(file => file.content).join('\n');
264
+ const androidEntrypoints = files.filter(file => /(^|\/)android\/(?:.*\/)?MainApplication\.(kt|java)$/.test(file.path));
265
+ const iosEntrypoints = files.filter(file => /(^|\/)ios\/(?:.*\/)?AppDelegate\.(swift|m|mm)$/.test(file.path));
266
+ const codeContent = files.map(file => codeLikeContent(file.content)).join('\n');
267
+ const androidLanguage = files.some(file => file.path.endsWith('MainApplication.kt'))
268
+ ? 'kotlin'
269
+ : files.some(file => file.path.endsWith('MainApplication.java'))
270
+ ? 'java'
271
+ : 'unknown';
272
+ const iosLanguage = files.some(file => file.path.endsWith('AppDelegate.swift'))
273
+ ? 'swift'
274
+ : files.some(file => file.path.endsWith('AppDelegate.m') || file.path.endsWith('AppDelegate.mm'))
275
+ ? 'objc'
276
+ : 'unknown';
277
+ const signals = [
278
+ 'ReactNativeHost',
279
+ 'ReactHost',
280
+ 'getDefaultReactHost',
281
+ 'loadReactNative',
282
+ 'getJSBundleFile',
283
+ 'bundleURL',
284
+ 'sourceURLForBridge',
285
+ 'bundle-drop-config',
286
+ ].filter(signal => allContent.includes(signal));
287
+ if (androidEntrypoints.length > 1)
288
+ signals.push('multipleAndroidEntrypoints');
289
+ if (iosEntrypoints.length > 1)
290
+ signals.push('multipleIosEntrypoints');
291
+ return {
292
+ rnVersion: null,
293
+ androidLanguage,
294
+ iosLanguage,
295
+ signals,
296
+ existingBundleDrop: hasBundleDropResolverCall(codeContent),
297
+ };
298
+ };
299
+ const readAuthToken = () => {
300
+ const authPath = path_1.default.join(os_1.default.homedir(), '.bundle-drop', 'auth.json');
301
+ if (!fs_extra_1.default.existsSync(authPath)) {
302
+ throw new Error('Not authenticated. Please run `bundle-drop login` before `bundle-drop init-native`.');
303
+ }
304
+ try {
305
+ const parsed = readJsonFile(authPath);
306
+ if (typeof parsed.token !== 'string' || !parsed.token.trim()) {
307
+ throw new Error('Token missing');
308
+ }
309
+ return parsed.token.trim();
310
+ }
311
+ catch {
312
+ throw new Error('Failed to read CLI auth session. Please run `bundle-drop login` again.');
313
+ }
314
+ };
315
+ function scanProjectForAiNativeInit(startDir = process.cwd()) {
316
+ const projectRoot = findProjectRoot(startDir);
317
+ const configPath = path_1.default.join(projectRoot, 'bundle.drop.config.js');
318
+ if (!fs_extra_1.default.existsSync(configPath)) {
319
+ throw new Error('bundle.drop.config.js not found; run `bundle-drop init` first.');
320
+ }
321
+ const config = loadBundleDropConfig(configPath);
322
+ const serverUrl = typeof config.serverUrl === 'string' ? normalizeServerUrl(config.serverUrl) : '';
323
+ const orgSlug = typeof config.org?.slug === 'string' ? config.org.slug.trim() : '';
324
+ const projectSlug = typeof config.project?.slug === 'string' ? config.project.slug.trim() : '';
325
+ if (!serverUrl || !orgSlug || !projectSlug) {
326
+ throw new Error('Missing "serverUrl", "org.slug" or "project.slug" in bundle.drop.config.js.');
327
+ }
328
+ if (!(0, exports.isTrustedAiPlanningServer)(serverUrl)) {
329
+ throw new Error(`Refusing to send project files to untrusted AI planning server: ${serverUrl}. ` +
330
+ 'Use https://api.bundledrop.app or a local development server.');
331
+ }
332
+ const files = collectFiles(projectRoot);
333
+ const detected = detectSignals(files);
334
+ detected.rnVersion = detectRnVersion(projectRoot);
335
+ return {
336
+ projectRoot,
337
+ serverUrl,
338
+ orgSlug,
339
+ projectSlug,
340
+ authToken: readAuthToken(),
341
+ request: {
342
+ schemaVersion: 1,
343
+ orgSlug,
344
+ projectSlug,
345
+ detected,
346
+ files,
347
+ },
348
+ };
349
+ }
@@ -0,0 +1,53 @@
1
+ export type AiInitConfidence = 'high' | 'medium' | 'low';
2
+ export type AiInitDecisionType = 'safe_auto_patch' | 'review_only_patch' | 'manual_fallback' | 'skip';
3
+ export type AiInitDetected = {
4
+ rnVersion: string | null;
5
+ androidLanguage: 'kotlin' | 'java' | 'unknown';
6
+ iosLanguage: 'swift' | 'objc' | 'unknown';
7
+ signals: string[];
8
+ existingBundleDrop: boolean;
9
+ };
10
+ export type AiInitPlanFile = {
11
+ path: string;
12
+ content: string;
13
+ sha256: string;
14
+ };
15
+ export type AiInitPlanRequest = {
16
+ schemaVersion: 1;
17
+ orgSlug: string;
18
+ projectSlug: string;
19
+ detected: AiInitDetected;
20
+ files: AiInitPlanFile[];
21
+ };
22
+ export type AiPatchPlan = {
23
+ file: string;
24
+ originalSha256: string;
25
+ updated: string;
26
+ reason: string;
27
+ confidence: AiInitConfidence;
28
+ decisionType: AiInitDecisionType;
29
+ };
30
+ export type AiInitQuestion = {
31
+ id: string;
32
+ severity: 'info' | 'warning' | 'risky';
33
+ file?: string | null;
34
+ message: string;
35
+ prompt: string;
36
+ recommendedChoice: 'yes' | 'no';
37
+ yesAction?: AiPatchPlan | null;
38
+ noAction?: AiPatchPlan | 'manual_fallback' | 'skip' | null;
39
+ };
40
+ export type AiInitPlanResponse = {
41
+ confidence: AiInitConfidence;
42
+ summary: string;
43
+ changes: AiPatchPlan[];
44
+ questions: AiInitQuestion[];
45
+ };
46
+ export type AiScannerResult = {
47
+ projectRoot: string;
48
+ serverUrl: string;
49
+ orgSlug: string;
50
+ projectSlug: string;
51
+ authToken: string;
52
+ request: AiInitPlanRequest;
53
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,8 @@
1
+ import { AiPatchPlan } from './types';
2
+ export declare const isSafeRelativePath: (value: string) => boolean;
3
+ export declare const isPatchableNativeEntrypoint: (filePath: string) => boolean;
4
+ export declare function validateChangesBeforeApply(params: {
5
+ originals: Map<string, string>;
6
+ changes: AiPatchPlan[];
7
+ }): void;
8
+ export declare function validateAppliedChanges(projectRoot: string, changes: AiPatchPlan[]): void;
@@ -0,0 +1,164 @@
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.isPatchableNativeEntrypoint = exports.isSafeRelativePath = void 0;
7
+ exports.validateChangesBeforeApply = validateChangesBeforeApply;
8
+ exports.validateAppliedChanges = validateAppliedChanges;
9
+ const crypto_1 = __importDefault(require("crypto"));
10
+ const fs_extra_1 = __importDefault(require("fs-extra"));
11
+ const path_1 = __importDefault(require("path"));
12
+ const sha256 = (content) => crypto_1.default.createHash('sha256').update(content).digest('hex');
13
+ const isSafeRelativePath = (value) => {
14
+ if (!value || value.startsWith('/') || value.includes('\\'))
15
+ return false;
16
+ const normalized = value.split('/').filter(Boolean).join('/');
17
+ return normalized === value && !normalized.split('/').includes('..');
18
+ };
19
+ exports.isSafeRelativePath = isSafeRelativePath;
20
+ const isPatchableNativeEntrypoint = (filePath) => /(^|\/)android\/(?:.*\/)?MainApplication\.(kt|java)$/.test(filePath) ||
21
+ /(^|\/)ios\/(?:.*\/)?AppDelegate\.(swift|m|mm)$/.test(filePath);
22
+ exports.isPatchableNativeEntrypoint = isPatchableNativeEntrypoint;
23
+ const codeLikeContent = (content) => {
24
+ let result = '';
25
+ let state = 'code';
26
+ for (let i = 0; i < content.length; i++) {
27
+ const char = content[i];
28
+ const next = content[i + 1];
29
+ if (state === 'line-comment') {
30
+ if (char === '\n') {
31
+ state = 'code';
32
+ result += char;
33
+ }
34
+ continue;
35
+ }
36
+ if (state === 'block-comment') {
37
+ if (char === '*' && next === '/') {
38
+ state = 'code';
39
+ i++;
40
+ }
41
+ continue;
42
+ }
43
+ if (state === 'single' || state === 'double' || state === 'template') {
44
+ if (char === '\\') {
45
+ i++;
46
+ continue;
47
+ }
48
+ if ((state === 'single' && char === "'") ||
49
+ (state === 'double' && char === '"') ||
50
+ (state === 'template' && char === '`')) {
51
+ state = 'code';
52
+ }
53
+ continue;
54
+ }
55
+ if (char === '/' && next === '/') {
56
+ state = 'line-comment';
57
+ i++;
58
+ continue;
59
+ }
60
+ if (char === '/' && next === '*') {
61
+ state = 'block-comment';
62
+ i++;
63
+ continue;
64
+ }
65
+ if (char === "'") {
66
+ state = 'single';
67
+ continue;
68
+ }
69
+ if (char === '"') {
70
+ state = 'double';
71
+ continue;
72
+ }
73
+ if (char === '`') {
74
+ state = 'template';
75
+ continue;
76
+ }
77
+ result += char;
78
+ }
79
+ return result;
80
+ };
81
+ const hasBalancedPairs = (content) => {
82
+ const pairs = { ')': '(', '}': '{', ']': '[' };
83
+ const opens = new Set(Object.values(pairs));
84
+ const stack = [];
85
+ for (const char of codeLikeContent(content)) {
86
+ if (opens.has(char))
87
+ stack.push(char);
88
+ if (pairs[char] && stack.pop() !== pairs[char])
89
+ return false;
90
+ }
91
+ return stack.length === 0;
92
+ };
93
+ const hasAndroidBundleDropIntegration = (content) => {
94
+ const code = codeLikeContent(content);
95
+ return /getJSBundleFile[\s\S]{0,2500}BundleDropModule\.resolveJSBundleFile|BundleDropModule\.resolveJSBundleFile[\s\S]{0,2500}getJSBundleFile/.test(code);
96
+ };
97
+ const hasIosBundleDropIntegration = (content) => {
98
+ const code = codeLikeContent(content);
99
+ return (/bundleURL[\s\S]{0,2500}BundleDropLocator\.bundleURL\(\)|BundleDropLocator\.bundleURL\(\)[\s\S]{0,2500}bundleURL/.test(code) ||
100
+ /sourceURLForBridge[\s\S]{0,2500}\[BundleDropLocator bundleURL\]|\[BundleDropLocator bundleURL\][\s\S]{0,2500}sourceURLForBridge/.test(code));
101
+ };
102
+ function validateChangesBeforeApply(params) {
103
+ const seen = new Set();
104
+ for (const change of params.changes) {
105
+ if (!(0, exports.isSafeRelativePath)(change.file)) {
106
+ throw new Error(`AI plan references an unsafe file path: ${change.file}`);
107
+ }
108
+ if (!(0, exports.isPatchableNativeEntrypoint)(change.file)) {
109
+ throw new Error(`AI plan references a non-native entrypoint: ${change.file}`);
110
+ }
111
+ if (!params.originals.has(change.file)) {
112
+ throw new Error(`AI plan references a file that was not scanned: ${change.file}`);
113
+ }
114
+ if (seen.has(change.file)) {
115
+ throw new Error(`AI plan contains multiple updates for ${change.file}`);
116
+ }
117
+ seen.add(change.file);
118
+ if (sha256(params.originals.get(change.file) || '') !== change.originalSha256) {
119
+ throw new Error(`AI plan hash mismatch for ${change.file}`);
120
+ }
121
+ if (!change.updated.trim()) {
122
+ throw new Error(`AI plan returned an empty update for ${change.file}`);
123
+ }
124
+ if (change.updated.includes('TODO_BUNDLEDROP') || change.updated.includes('<TODO')) {
125
+ throw new Error(`AI plan returned placeholder text in ${change.file}`);
126
+ }
127
+ if (!hasBalancedPairs(change.updated)) {
128
+ throw new Error(`AI plan returned unbalanced braces or brackets in ${change.file}`);
129
+ }
130
+ if ((change.file.startsWith('android/') || change.file.includes('/android/')) &&
131
+ !hasAndroidBundleDropIntegration(change.updated)) {
132
+ throw new Error(`AI plan Android update does not contain BundleDrop resolver: ${change.file}`);
133
+ }
134
+ if ((change.file.startsWith('ios/') || change.file.includes('/ios/')) &&
135
+ !hasIosBundleDropIntegration(change.updated)) {
136
+ throw new Error(`AI plan iOS update does not contain BundleDrop locator: ${change.file}`);
137
+ }
138
+ }
139
+ }
140
+ function validateAppliedChanges(projectRoot, changes) {
141
+ for (const change of changes) {
142
+ if (!(0, exports.isSafeRelativePath)(change.file) || !(0, exports.isPatchableNativeEntrypoint)(change.file)) {
143
+ throw new Error(`Updated file path is not allowed: ${change.file}`);
144
+ }
145
+ const content = fs_extra_1.default.readFileSync(path_1.default.join(projectRoot, change.file), 'utf8');
146
+ if (!content.trim()) {
147
+ throw new Error(`Updated file is empty: ${change.file}`);
148
+ }
149
+ if (content.includes('TODO_BUNDLEDROP') || content.includes('<TODO')) {
150
+ throw new Error(`Updated file contains placeholder text: ${change.file}`);
151
+ }
152
+ if (!hasBalancedPairs(content)) {
153
+ throw new Error(`Updated file has unbalanced braces or brackets: ${change.file}`);
154
+ }
155
+ if ((change.file.startsWith('android/') || change.file.includes('/android/')) &&
156
+ !hasAndroidBundleDropIntegration(content)) {
157
+ throw new Error(`Android update does not contain BundleDrop resolver: ${change.file}`);
158
+ }
159
+ if ((change.file.startsWith('ios/') || change.file.includes('/ios/')) &&
160
+ !hasIosBundleDropIntegration(content)) {
161
+ throw new Error(`iOS update does not contain BundleDrop locator: ${change.file}`);
162
+ }
163
+ }
164
+ }
@@ -89,15 +89,20 @@ async function initConfig(params) {
89
89
  }
90
90
  }
91
91
  // Project selection
92
- if (!params.projects?.length) {
92
+ const allProjects = params.projects || [];
93
+ const selectedOrg = orgSlug ? params.organizations.find(o => o.slug === orgSlug) : undefined;
94
+ const projectChoices = selectedOrg
95
+ ? allProjects.filter(p => p.orgId === selectedOrg.orgId)
96
+ : allProjects;
97
+ if (!projectChoices.length) {
93
98
  console.log(chalk_1.default.red(`⚠️ No projects returned; project values will be left blank.\n` +
94
99
  `Create a project first: ${DOCS_PROJECT_CREATION_URL}`));
95
100
  }
96
- else if (params.projects.length === 1) {
97
- project = params.projects[0];
101
+ else if (projectChoices.length === 1) {
102
+ project = projectChoices[0];
98
103
  }
99
104
  else {
100
- const choices = params.projects.map(p => ({
105
+ const choices = projectChoices.map(p => ({
101
106
  title: `${p.name} (${p.slug})`,
102
107
  value: p.slug,
103
108
  }));
@@ -107,7 +112,7 @@ async function initConfig(params) {
107
112
  message: 'Select a project to target:',
108
113
  choices,
109
114
  });
110
- project = params.projects.find(p => p.slug === projectSlug) || null;
115
+ project = projectChoices.find(p => p.slug === projectSlug) || null;
111
116
  if (!project) {
112
117
  console.log(chalk_1.default.yellow('⚠️ No project selected; project values will be left blank.'));
113
118
  }
@@ -450,7 +450,7 @@ function patchIosAppDelegateObjc(filePath) {
450
450
  return;
451
451
  }
452
452
  // Ensure import
453
- const importLine = '#import <BundleDrop/BundleDrop-Swift.h>';
453
+ const importLine = '#import <BundleDrop/BundleDropLocator.h>';
454
454
  if (!content.includes(importLine)) {
455
455
  const reactImport = content.match(/^#import\s+<React\/[^>]+>.*$/m);
456
456
  if (reactImport) {
@@ -26,23 +26,12 @@ async function runPostInitPrompts() {
26
26
  `See ${DOCS_METRO_SETUP_URL} (${err?.message || err})`);
27
27
  }
28
28
  }
29
- // Offer to patch native entrypoints (after Metro prompt finishes)
30
- const nativeAnswer = await (0, prompts_1.default)({
31
- type: 'confirm',
32
- name: 'runNative',
33
- message: 'Patch native entrypoints (MainApplication/AppDelegate) to prefer OTA? (Standard RN setups only)',
34
- initial: false,
35
- });
36
- if (nativeAnswer.runNative) {
37
- try {
38
- //eslint-disable-next-line
39
- await require('./init-native-config').initNativeConfig();
40
- console.log(`⚠️ Please double-check the native changes in MainApplication/AppDelegate.\n` +
41
- `See ${DOCS_NATIVE_SETUP_URL}`);
42
- }
43
- catch (err) {
44
- console.log(`⚠️ Failed to initialize native config; please refer to manual setup instructions.\n` +
45
- `See ${DOCS_NATIVE_SETUP_URL} (${err?.message || err})`);
46
- }
29
+ try {
30
+ //eslint-disable-next-line
31
+ await require('./aipowered/init-native-config').initNativeConfigAi();
32
+ }
33
+ catch (err) {
34
+ console.log(`⚠️ Failed to initialize native config; please refer to manual setup instructions.\n` +
35
+ `See ${DOCS_NATIVE_SETUP_URL} (${err?.message || err})`);
47
36
  }
48
37
  }
@@ -7,4 +7,6 @@ export default function upload(platform: string, options: {
7
7
  releaseNotes?: string;
8
8
  token?: string;
9
9
  author?: string;
10
+ sourcemap?: boolean;
11
+ artifactDir?: string;
10
12
  }): Promise<void>;