@gfean/react-native-bundle-drop 0.6.0 → 0.8.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 (86) hide show
  1. package/BundleDrop.podspec +96 -0
  2. package/README.md +249 -9
  3. package/android/build.gradle +72 -5
  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 +9 -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/sight-artifacts.d.ts +9 -1
  23. package/lib/CLI/scripts/sight-artifacts.js +20 -8
  24. package/lib/CLI/scripts/sight-assets.d.ts +15 -0
  25. package/lib/CLI/scripts/sight-assets.js +71 -0
  26. package/lib/CLI/scripts/sight-cli.d.ts +3 -0
  27. package/lib/CLI/scripts/sight-cli.js +50 -4
  28. package/lib/CLI/scripts/sight-compare/assets.d.ts +6 -0
  29. package/lib/CLI/scripts/sight-compare/assets.js +73 -0
  30. package/lib/CLI/scripts/sight-compare/dependencies.d.ts +22 -0
  31. package/lib/CLI/scripts/sight-compare/dependencies.js +289 -0
  32. package/lib/CLI/scripts/sight-compare/git.d.ts +22 -0
  33. package/lib/CLI/scripts/sight-compare/git.js +116 -0
  34. package/lib/CLI/scripts/sight-compare/inspect-project.d.ts +37 -0
  35. package/lib/CLI/scripts/sight-compare/inspect-project.js +191 -0
  36. package/lib/CLI/scripts/sight-compare/metadata.d.ts +4 -0
  37. package/lib/CLI/scripts/sight-compare/metadata.js +39 -0
  38. package/lib/CLI/scripts/sight-compare/process.d.ts +22 -0
  39. package/lib/CLI/scripts/sight-compare/process.js +221 -0
  40. package/lib/CLI/scripts/sight-compare/run.d.ts +3 -0
  41. package/lib/CLI/scripts/sight-compare/run.js +290 -0
  42. package/lib/CLI/scripts/sight-compare/snapshot.d.ts +26 -0
  43. package/lib/CLI/scripts/sight-compare/snapshot.js +279 -0
  44. package/lib/CLI/scripts/sight-compare/types.d.ts +87 -0
  45. package/lib/CLI/scripts/sight-compare/types.js +2 -0
  46. package/lib/CLI/scripts/sight-ota.d.ts +18 -0
  47. package/lib/CLI/scripts/sight-ota.js +260 -0
  48. package/lib/CLI/scripts/sight-session.d.ts +9 -2
  49. package/lib/CLI/scripts/sight-session.js +58 -20
  50. package/lib/CLI/scripts/upload-cli.d.ts +12 -2
  51. package/lib/CLI/scripts/upload-cli.js +74 -11
  52. package/lib/CLI/serverUrl.d.ts +3 -0
  53. package/lib/CLI/serverUrl.js +31 -0
  54. package/lib/bundleInfo.d.ts +2 -0
  55. package/lib/bundleInfo.js +16 -1
  56. package/lib/context.js +12 -2
  57. package/lib/fs/bundlePointer.d.ts +1 -17
  58. package/lib/fs/bundlePointer.js +5 -93
  59. package/lib/install/bundleInstallShared.js +4 -4
  60. package/lib/manager/downloadAndInstall.js +25 -22
  61. package/lib/manager/reporting.d.ts +8 -1
  62. package/lib/manager/reporting.js +17 -22
  63. package/lib/manager/rollbackState.d.ts +18 -54
  64. package/lib/manager/rollbackState.js +115 -216
  65. package/lib/manager/updateCheck.js +9 -3
  66. package/lib/manager/updateState.d.ts +2 -1
  67. package/lib/manager/updateState.js +59 -6
  68. package/lib/metro.d.ts +1 -1
  69. package/lib/metro.js +4 -3
  70. package/lib/native/bundleDropNative.d.ts +62 -0
  71. package/lib/native/bundleDropNative.js +266 -1
  72. package/lib/patch-engine/installFromPatchSet.js +2 -2
  73. package/lib/runtime/service.js +29 -71
  74. package/lib/runtime-delivery/bootstrapConfig.d.ts +29 -11
  75. package/lib/runtime-delivery/bootstrapConfig.js +83 -22
  76. package/lib/runtime-delivery/manifestState.d.ts +3 -1
  77. package/lib/runtime-delivery/manifestState.js +22 -1
  78. package/lib/runtime-delivery/manifestVerifier.js +7 -1
  79. package/lib/scripts/bundle.d.ts +12 -2
  80. package/lib/scripts/bundle.js +74 -21
  81. package/lib/scripts/download-bundle.d.ts +1 -0
  82. package/lib/scripts/download-bundle.js +2 -2
  83. package/lib/scripts/resolveModule.d.ts +2 -0
  84. package/lib/scripts/resolveModule.js +5 -0
  85. package/package.json +5 -2
  86. package/plugin/xcodeBuildPhase.js +2 -1
@@ -0,0 +1,4 @@
1
+ import type { ComparisonArtifact, ComparisonArtifacts, ComparisonMetadata } from './types';
2
+ export declare const MAX_COMPARISON_METADATA_BYTES: number;
3
+ export declare function describeArtifact(outputDirectory: string, filePath: string): ComparisonArtifact;
4
+ export declare function writeComparisonMetadata(artifacts: ComparisonArtifacts, metadata: Omit<ComparisonMetadata, 'artifacts'>): ComparisonMetadata;
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.MAX_COMPARISON_METADATA_BYTES = void 0;
7
+ exports.describeArtifact = describeArtifact;
8
+ exports.writeComparisonMetadata = writeComparisonMetadata;
9
+ const crypto_1 = require("crypto");
10
+ const fs_1 = __importDefault(require("fs"));
11
+ const path_1 = __importDefault(require("path"));
12
+ exports.MAX_COMPARISON_METADATA_BYTES = 64 * 1024;
13
+ function describeArtifact(outputDirectory, filePath) {
14
+ const contents = fs_1.default.readFileSync(filePath);
15
+ return {
16
+ path: path_1.default.relative(outputDirectory, filePath).split(path_1.default.sep).join('/'),
17
+ bytes: contents.length,
18
+ sha256: (0, crypto_1.createHash)('sha256').update(contents).digest('hex'),
19
+ };
20
+ }
21
+ function writeComparisonMetadata(artifacts, metadata) {
22
+ const describe = (filePath) => describeArtifact(artifacts.outputDirectory, filePath);
23
+ const document = {
24
+ ...metadata,
25
+ artifacts: {
26
+ baselineBundle: describe(artifacts.baseline.bundlePath),
27
+ baselineSourceMap: describe(artifacts.baseline.sourceMapPath),
28
+ currentBundle: describe(artifacts.current.bundlePath),
29
+ currentSourceMap: describe(artifacts.current.sourceMapPath),
30
+ },
31
+ ...(artifacts.assetManifestPath ? { assetManifest: describe(artifacts.assetManifestPath) } : {}),
32
+ };
33
+ const json = JSON.stringify(document, null, 2) + '\n';
34
+ if (Buffer.byteLength(json) > exports.MAX_COMPARISON_METADATA_BYTES) {
35
+ throw new Error('Sight comparison metadata exceeds 64 KiB. Reduce the included paths and retry.');
36
+ }
37
+ fs_1.default.writeFileSync(artifacts.metadataPath, json, { mode: 0o600 });
38
+ return document;
39
+ }
@@ -0,0 +1,22 @@
1
+ export type ComparisonProcessOptions = {
2
+ command: string;
3
+ args: string[];
4
+ cwd: string;
5
+ phase: string;
6
+ signal?: AbortSignal;
7
+ env?: NodeJS.ProcessEnv;
8
+ logPath?: string;
9
+ inheritStdin?: boolean;
10
+ inheritOutput?: boolean;
11
+ input?: string;
12
+ allowedExitCodes?: number[];
13
+ };
14
+ export type ComparisonProcessResult = {
15
+ stdout: string;
16
+ stderr: string;
17
+ exitCode: number;
18
+ };
19
+ export declare function comparisonAbortError(): Error;
20
+ export declare function checkComparisonAbort(signal?: AbortSignal): void;
21
+ /** Run in a separate process group so cancelling also stops Metro/install children. */
22
+ export declare function runComparisonProcess({ command, args, cwd, phase, signal, env, logPath, inheritStdin, inheritOutput, input, allowedExitCodes, }: ComparisonProcessOptions): Promise<ComparisonProcessResult>;
@@ -0,0 +1,221 @@
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.comparisonAbortError = comparisonAbortError;
7
+ exports.checkComparisonAbort = checkComparisonAbort;
8
+ exports.runComparisonProcess = runComparisonProcess;
9
+ const child_process_1 = require("child_process");
10
+ const fs_1 = __importDefault(require("fs"));
11
+ const path_1 = __importDefault(require("path"));
12
+ function comparisonAbortError() {
13
+ const error = new Error('Sight comparison cancelled.');
14
+ error.name = 'AbortError';
15
+ return error;
16
+ }
17
+ function checkComparisonAbort(signal) {
18
+ if (signal?.aborted)
19
+ throw comparisonAbortError();
20
+ }
21
+ function redactOutput(output, env) {
22
+ let result = output.replace(/(https?:\/\/)[^\s/@]+@/gi, '$1[redacted]@');
23
+ for (const [name, value] of Object.entries(env)) {
24
+ if (/(token|password|secret|credential|authorization)/i.test(name) && value && value.length >= 4) {
25
+ result = result.split(value).join('[redacted]');
26
+ }
27
+ }
28
+ return result;
29
+ }
30
+ function windowsPackageManager(command, args, cwd, env) {
31
+ const manager = path_1.default.basename(command).match(/^(npm|yarn|pnpm)(?:\.(?:cmd|bat|exe|com))?$/i)?.[1]?.toLowerCase();
32
+ if (process.platform !== 'win32' || !manager)
33
+ return { command, args };
34
+ const variables = Object.fromEntries(Object.entries(env).map(([name, value]) => [name.toUpperCase(), value]));
35
+ const extensions = (variables.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').map(extension => extension.toLowerCase());
36
+ const directories = path_1.default.isAbsolute(command) || /[/\\]/.test(command)
37
+ ? [path_1.default.dirname(path_1.default.resolve(cwd, command))]
38
+ : (variables.PATH || '').split(';').filter(Boolean).map(directory => directory.replace(/^"|"$/g, ''));
39
+ const names = path_1.default.extname(command) ? [path_1.default.basename(command)] : extensions.map(extension => `${manager}${extension}`);
40
+ let executable;
41
+ for (const directory of directories) {
42
+ executable = names.map(name => path_1.default.resolve(directory, name)).find(file => fs_1.default.existsSync(file) && fs_1.default.statSync(file).isFile());
43
+ if (executable)
44
+ break;
45
+ }
46
+ if (!executable)
47
+ throw new Error(`Could not find ${manager} on PATH. Install the required package manager before comparing.`);
48
+ if (/\.(?:exe|com)$/i.test(executable))
49
+ return { command: executable, args };
50
+ if (/\.(?:cmd|bat)$/i.test(executable)) {
51
+ const directory = path_1.default.dirname(executable);
52
+ const entries = {
53
+ npm: 'npm/bin/npm-cli.js',
54
+ yarn: 'yarn/bin/yarn.js',
55
+ pnpm: 'pnpm/bin/pnpm.cjs',
56
+ };
57
+ const candidates = [
58
+ path_1.default.join(directory, 'node_modules', entries[manager]),
59
+ path_1.default.join(directory, 'node_modules', 'corepack', 'dist', `${manager}.js`),
60
+ ];
61
+ if (path_1.default.basename(directory) === '.bin') {
62
+ candidates.push(path_1.default.resolve(directory, '..', entries[manager]), path_1.default.resolve(directory, '..', 'corepack', 'dist', `${manager}.js`));
63
+ }
64
+ const script = candidates.find(file => fs_1.default.existsSync(file) && fs_1.default.statSync(file).isFile());
65
+ if (script)
66
+ return { command: process.execPath, args: [script, ...args] };
67
+ }
68
+ throw new Error(`Unsupported Windows ${manager} launcher. Install a standard Node/npm or Corepack package-manager shim, or provide its native executable on PATH.`);
69
+ }
70
+ async function waitForProcessGroupExit(pid, timeoutMs) {
71
+ const deadline = Date.now() + timeoutMs;
72
+ const permissionDeadline = Date.now() + Math.max(timeoutMs, 100);
73
+ while (true) {
74
+ try {
75
+ process.kill(-pid, 0);
76
+ }
77
+ catch (error) {
78
+ if (error.code === 'ESRCH')
79
+ return true;
80
+ // Darwin can report EPERM for a group containing only unreaped zombies.
81
+ // Require a later ESRCH; a persistent permission failure must still reject.
82
+ if (process.platform === 'darwin' && error.code === 'EPERM' && Date.now() < permissionDeadline) {
83
+ await new Promise(resolve => setTimeout(resolve, 20));
84
+ continue;
85
+ }
86
+ throw error;
87
+ }
88
+ if (Date.now() >= deadline)
89
+ return false;
90
+ await new Promise(resolve => setTimeout(resolve, 20));
91
+ }
92
+ }
93
+ async function stopRemainingProcessGroup(pid) {
94
+ // Windows taskkill requires a live leader; Job Object containment is not provided here.
95
+ if (process.platform === 'win32' || !pid || await waitForProcessGroupExit(pid, 0))
96
+ return;
97
+ for (const signal of ['SIGTERM', 'SIGKILL']) {
98
+ try {
99
+ process.kill(-pid, signal);
100
+ }
101
+ catch (error) {
102
+ if (error.code === 'ESRCH')
103
+ return;
104
+ throw error;
105
+ }
106
+ if (await waitForProcessGroupExit(pid, 1000))
107
+ return;
108
+ }
109
+ throw new Error('A comparison subprocess left a process group running after termination.');
110
+ }
111
+ /** Run in a separate process group so cancelling also stops Metro/install children. */
112
+ async function runComparisonProcess({ command, args, cwd, phase, signal, env = process.env, logPath, inheritStdin = false, inheritOutput = false, input, allowedExitCodes = [0], }) {
113
+ checkComparisonAbort(signal);
114
+ if (logPath)
115
+ fs_1.default.mkdirSync(path_1.default.dirname(logPath), { recursive: true });
116
+ const executable = windowsPackageManager(command, args, cwd, env);
117
+ return new Promise((resolve, reject) => {
118
+ const child = (0, child_process_1.spawn)(executable.command, executable.args, {
119
+ cwd,
120
+ env,
121
+ shell: false,
122
+ detached: process.platform !== 'win32',
123
+ windowsHide: true,
124
+ stdio: [input !== undefined ? 'pipe' : inheritStdin ? 'inherit' : 'ignore', inheritOutput ? 'inherit' : 'pipe', inheritOutput ? 'inherit' : 'pipe'],
125
+ });
126
+ let stdout = '';
127
+ let stderr = '';
128
+ let escalation;
129
+ let processError;
130
+ let windowsTermination;
131
+ let groupTermination;
132
+ let groupCleanupTimer;
133
+ const stopGroup = () => {
134
+ groupTermination ?? (groupTermination = stopRemainingProcessGroup(child.pid).catch(error => { processError = error; }));
135
+ return groupTermination;
136
+ };
137
+ const terminateGroup = (force) => {
138
+ if (!child.pid)
139
+ return;
140
+ if (process.platform === 'win32') {
141
+ const killer = (0, child_process_1.spawn)('taskkill', ['/pid', String(child.pid), '/t', '/f'], {
142
+ windowsHide: true,
143
+ stdio: 'ignore',
144
+ });
145
+ windowsTermination = new Promise(done => {
146
+ killer.once('error', () => { child.kill(); done(); });
147
+ killer.once('close', () => done());
148
+ });
149
+ }
150
+ else {
151
+ try {
152
+ process.kill(-child.pid, force ? 'SIGKILL' : 'SIGTERM');
153
+ }
154
+ catch (error) {
155
+ if (error.code !== 'ESRCH') {
156
+ processError = error;
157
+ child.kill(force ? 'SIGKILL' : 'SIGTERM');
158
+ }
159
+ }
160
+ }
161
+ };
162
+ const abort = () => {
163
+ terminateGroup(false);
164
+ if (process.platform !== 'win32') {
165
+ escalation = setTimeout(() => terminateGroup(true), 1000);
166
+ }
167
+ };
168
+ child.stdout?.setEncoding('utf8');
169
+ if (input !== undefined) {
170
+ child.stdin.on('error', error => { processError = error; });
171
+ child.stdin.end(input);
172
+ }
173
+ child.stderr?.setEncoding('utf8');
174
+ child.stdout?.on('data', (chunk) => { stdout += chunk; });
175
+ child.stderr?.on('data', (chunk) => { stderr += chunk; });
176
+ child.once('error', error => { processError = error; });
177
+ // Descendants can keep the output pipes open after the leader exits, delaying close.
178
+ child.once('exit', () => {
179
+ // Give normally exiting children a turn to release their pipes and process group.
180
+ groupCleanupTimer = setTimeout(stopGroup, 20);
181
+ });
182
+ child.once('close', async (code, exitSignal) => {
183
+ if (groupCleanupTimer)
184
+ clearTimeout(groupCleanupTimer);
185
+ signal?.removeEventListener('abort', abort);
186
+ if (escalation) {
187
+ // The leader may exit before descendants; finish killing its group before cleanup.
188
+ clearTimeout(escalation);
189
+ terminateGroup(true);
190
+ }
191
+ await windowsTermination;
192
+ await stopGroup();
193
+ const safeStdout = redactOutput(stdout, env);
194
+ const safeStderr = redactOutput(stderr, env);
195
+ try {
196
+ if (logPath)
197
+ fs_1.default.writeFileSync(logPath, `${safeStdout}${safeStderr}`, { mode: 0o600 });
198
+ }
199
+ catch (error) {
200
+ reject(error);
201
+ return;
202
+ }
203
+ if (signal?.aborted) {
204
+ reject(comparisonAbortError());
205
+ }
206
+ else if (processError) {
207
+ reject(new Error(`${phase} could not start or finish: ${redactOutput(processError.message, env)}`));
208
+ }
209
+ else if (code === null || !allowedExitCodes.includes(code)) {
210
+ const detail = safeStderr.trim().slice(-2000);
211
+ reject(new Error(`${phase} failed (${exitSignal || `exit ${code}`}).${detail ? `\n${detail}` : ''}`));
212
+ }
213
+ else {
214
+ resolve({ stdout, stderr: safeStderr, exitCode: code });
215
+ }
216
+ });
217
+ signal?.addEventListener('abort', abort, { once: true });
218
+ if (signal?.aborted)
219
+ abort();
220
+ });
221
+ }
@@ -0,0 +1,3 @@
1
+ import type { SightCommandOptions } from '../sight-cli';
2
+ export declare function comparisonEnvironment(source: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
3
+ export declare function runSightComparison(options: SightCommandOptions): Promise<void>;
@@ -0,0 +1,290 @@
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.comparisonEnvironment = comparisonEnvironment;
7
+ exports.runSightComparison = runSightComparison;
8
+ const crypto_1 = require("crypto");
9
+ const fs_1 = __importDefault(require("fs"));
10
+ const os_1 = __importDefault(require("os"));
11
+ const path_1 = __importDefault(require("path"));
12
+ const prompts_1 = __importDefault(require("prompts"));
13
+ const chalk_1 = __importDefault(require("chalk"));
14
+ const logo_1 = require("../../logo");
15
+ const sight_artifacts_1 = require("../sight-artifacts");
16
+ const sight_ota_1 = require("../sight-ota");
17
+ const sight_session_1 = require("../sight-session");
18
+ const dependencies_1 = require("./dependencies");
19
+ const inspect_project_1 = require("./inspect-project");
20
+ const metadata_1 = require("./metadata");
21
+ const assets_1 = require("./assets");
22
+ const process_1 = require("./process");
23
+ const snapshot_1 = require("./snapshot");
24
+ const SIGHT_URL = 'https://bundledrop.app/sight';
25
+ function comparisonEnvironment(source) {
26
+ const env = { ...source };
27
+ for (const name of [
28
+ 'GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR',
29
+ 'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'INIT_CWD', 'PWD', 'NODE_PATH',
30
+ ])
31
+ delete env[name];
32
+ return env;
33
+ }
34
+ function configurationFingerprint(plan) {
35
+ const hash = (0, crypto_1.createHash)('sha256');
36
+ const files = new Set(plan.inputFiles);
37
+ for (const directory of new Set([plan.installRoot, plan.projectRoot])) {
38
+ for (const name of fs_1.default.readdirSync(directory)) {
39
+ if (/^(?:(?:metro|babel|app)\.config\.[cm]?[jt]s|bundle\.drop\.config\.js|app\.json|tsconfig\.json|\.babelrc(?:\.json|\.[cm]?js)?)$/.test(name)) {
40
+ const file = path_1.default.join(directory, name);
41
+ if (fs_1.default.statSync(file).isFile())
42
+ files.add(file);
43
+ }
44
+ }
45
+ }
46
+ for (const file of [...files].sort()) {
47
+ hash.update(path_1.default.relative(plan.snapshotRoot, file).split(path_1.default.sep).join('/'));
48
+ hash.update('\0');
49
+ hash.update(fs_1.default.readFileSync(file));
50
+ hash.update('\0');
51
+ }
52
+ return hash.digest('hex');
53
+ }
54
+ async function selectPlatform(projectRoot, platform) {
55
+ if (platform)
56
+ return platform;
57
+ const available = ['ios', 'android'].filter(name => fs_1.default.existsSync(path_1.default.join(projectRoot, name)));
58
+ if (available.length === 1)
59
+ return available[0];
60
+ if (!process.stdin.isTTY)
61
+ throw new Error('Pass --platform ios or --platform android for noninteractive comparison.');
62
+ const answer = await (0, prompts_1.default)({
63
+ type: 'select', name: 'platform', message: 'Which platform should Sight compare?',
64
+ choices: [{ title: 'iOS', value: 'ios' }, { title: 'Android', value: 'android' }],
65
+ });
66
+ if (!answer.platform)
67
+ throw new Error('No platform was selected.');
68
+ return answer.platform;
69
+ }
70
+ function outputDirectory(projectRoot, requested) {
71
+ if (!requested)
72
+ return fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), 'bundle-drop-sight-comparison-'));
73
+ const directory = path_1.default.resolve(projectRoot, requested);
74
+ if (fs_1.default.existsSync(directory)) {
75
+ if (!fs_1.default.lstatSync(directory).isDirectory() || fs_1.default.lstatSync(directory).isSymbolicLink() || fs_1.default.readdirSync(directory).length) {
76
+ throw new Error('Sight comparison output must be an empty real directory.');
77
+ }
78
+ }
79
+ else
80
+ fs_1.default.mkdirSync(directory, { recursive: true, mode: 0o700 });
81
+ return directory;
82
+ }
83
+ function manualInstructions(artifacts) {
84
+ console.log(chalk_1.default.green(`\nComparison files: ${artifacts.outputDirectory}`));
85
+ console.log(` Metadata: ${artifacts.metadataPath}`);
86
+ console.log(` Assets: ${artifacts.assetManifestPath}`);
87
+ console.log(` Baseline: ${artifacts.baseline.bundlePath}`);
88
+ console.log(` ${artifacts.baseline.sourceMapPath}`);
89
+ console.log(` Current: ${artifacts.current.bundlePath}`);
90
+ console.log(` ${artifacts.current.sourceMapPath}`);
91
+ console.log(`Open ${SIGHT_URL}, choose Compare, and attach the four bundle/map files for a JavaScript-only comparison.`);
92
+ console.log('Git labels, build context and asset sizes are included through automatic CLI loading.');
93
+ }
94
+ async function runSightComparison(options) {
95
+ if (!options.compare?.trim())
96
+ throw new Error('--compare requires a Git ref.');
97
+ const projectRoot = process.cwd();
98
+ const platform = await selectPlatform(projectRoot, options.platform);
99
+ const environment = comparisonEnvironment(process.env);
100
+ const buildEnvironment = { ...environment, NODE_ENV: 'production', BUNDLE_DROP_OTA_BUILD: '1' };
101
+ const controller = new AbortController();
102
+ const cancel = () => controller.abort(new Error('Sight comparison cancelled.'));
103
+ process.once('SIGINT', cancel);
104
+ process.once('SIGTERM', cancel);
105
+ const diagnostics = fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), 'bundle-drop-sight-logs-'));
106
+ let snapshots;
107
+ let artifacts;
108
+ let directory;
109
+ let complete = false;
110
+ let succeeded = false;
111
+ try {
112
+ console.log((0, logo_1.buildBundleDropLogo)());
113
+ console.log(chalk_1.default.bold.cyan('\nBundle Drop Sight — Compare'));
114
+ snapshots = await (0, snapshot_1.createComparisonSnapshots)({
115
+ projectRoot, compareRef: options.compare, fetch: options.fetch,
116
+ include: options.include, signal: controller.signal,
117
+ });
118
+ console.log(chalk_1.default.gray(`Baseline: ${snapshots.baselineLabel} → ${snapshots.baselineCommit}`));
119
+ console.log(chalk_1.default.gray(`Current: ${snapshots.currentLabel} → ${snapshots.currentCommit}${snapshots.currentDirty ? ' + working-tree changes' : ''}`));
120
+ console.log(chalk_1.default.gray(`Platform: ${platform} · production · minified JavaScript`));
121
+ console.log(chalk_1.default.gray('Metric: raw JavaScript bytes'));
122
+ console.log(chalk_1.default.gray('Assets: emitted file bytes, measured separately'));
123
+ console.log(chalk_1.default.green('✓ Captured current source files'));
124
+ const relativeApp = path_1.default.relative(snapshots.currentRoot, snapshots.currentProjectRoot);
125
+ const common = { signal: controller.signal, env: environment };
126
+ const plans = {
127
+ baseline: await (0, dependencies_1.inspectDependencyPlan)({ ...common, snapshotRoot: snapshots.baselineRoot, projectRelativePath: relativeApp }),
128
+ current: await (0, dependencies_1.inspectDependencyPlan)({ ...common, snapshotRoot: snapshots.currentRoot, projectRelativePath: relativeApp }),
129
+ };
130
+ const configuration = {
131
+ baseline: configurationFingerprint(plans.baseline),
132
+ current: configurationFingerprint(plans.current),
133
+ };
134
+ directory = outputDirectory(projectRoot, options.output);
135
+ console.log(chalk_1.default.yellow('Dependency installs may download packages and run project scripts.'));
136
+ for (const side of ['baseline', 'current']) {
137
+ await snapshots.assertIdentity();
138
+ await (0, dependencies_1.installDependencies)(plans[side], { ...common, logPath: path_1.default.join(diagnostics, `${side}-install.log`) });
139
+ await snapshots.assertIdentity();
140
+ console.log(chalk_1.default.green(`✓ Installed ${side} dependencies`));
141
+ }
142
+ const current = await (0, inspect_project_1.inspectSightProject)({
143
+ snapshotRoot: snapshots.currentRoot, projectRoot: snapshots.currentProjectRoot, platform,
144
+ explicitType: options.projectType, entryFile: options.entryFile,
145
+ }, { ...common, env: buildEnvironment });
146
+ const baseline = await (0, inspect_project_1.inspectSightProject)({
147
+ snapshotRoot: snapshots.baselineRoot, projectRoot: snapshots.baselineProjectRoot, platform,
148
+ explicitType: options.projectType, logicalEntry: current.entry,
149
+ }, { ...common, env: buildEnvironment });
150
+ if (baseline.projectType !== current.projectType)
151
+ throw new Error('Baseline and current have different project types; Sight cannot compare these builds.');
152
+ const inspected = { baseline, current };
153
+ const pairs = {};
154
+ const sides = {};
155
+ const assetEntries = {};
156
+ const ota = {};
157
+ for (const side of ['baseline', 'current']) {
158
+ const plan = plans[side];
159
+ const temp = path_1.default.join(snapshots.directory, `${side}-cache`);
160
+ const assetsDirectory = path_1.default.join(snapshots.directory, `${side}-assets`);
161
+ fs_1.default.mkdirSync(temp, { recursive: true });
162
+ const env = { ...buildEnvironment, TMPDIR: temp, TMP: temp, TEMP: temp };
163
+ await snapshots.assertIdentity();
164
+ pairs[side] = await (0, sight_artifacts_1.generateSightArtifacts)({
165
+ projectRoot: plan.projectRoot, projectType: inspected[side].projectType, platform,
166
+ entryFile: inspected[side].resolvedEntryFile, output: path_1.default.join(directory, side),
167
+ sourceMapRoot: plan.snapshotRoot,
168
+ assetsDirectory,
169
+ runCommand: async (cwd, command, args) => {
170
+ await (0, process_1.runComparisonProcess)({
171
+ command: process.execPath, args: [command, ...args], cwd, env,
172
+ phase: `Build ${side}`, signal: controller.signal,
173
+ logPath: path_1.default.join(diagnostics, `${side}-build.log`),
174
+ });
175
+ },
176
+ });
177
+ await snapshots.assertIdentity();
178
+ if (configurationFingerprint(plan) !== configuration[side]) {
179
+ throw new Error(`The ${side} build modified its dependency or build configuration inputs.`);
180
+ }
181
+ assetEntries[side] = await (0, assets_1.collectComparisonAssets)(assetsDirectory, controller.signal);
182
+ console.log(chalk_1.default.gray(`Measuring ${side} Bundle Drop OTA archive with its JavaScript engine…`));
183
+ ota[side] = await (0, sight_ota_1.measureSightOta)({
184
+ projectRoot: plan.projectRoot, snapshotRoot: plan.snapshotRoot,
185
+ projectType: inspected[side].projectType, platform,
186
+ entryFile: inspected[side].resolvedEntryFile,
187
+ bundlePath: pairs[side].bundlePath, sourceMapPath: pairs[side].sourceMapPath,
188
+ assetsDirectory, workDirectory: snapshots.directory,
189
+ }, { signal: controller.signal, env, logPath: path_1.default.join(diagnostics, `${side}-ota.log`) });
190
+ await snapshots.assertIdentity();
191
+ if (configurationFingerprint(plan) !== configuration[side]) {
192
+ throw new Error(`The ${side} OTA measurement modified its dependency or build configuration inputs.`);
193
+ }
194
+ const measurement = ota[side];
195
+ console.log(measurement.status === 'available'
196
+ ? chalk_1.default.green(`✓ ${side} Bundle Drop OTA size: ${measurement.zipBytes} bytes (${measurement.engine})`)
197
+ : chalk_1.default.yellow(`${side} Bundle Drop OTA size unavailable: ${measurement.reason}`));
198
+ fs_1.default.rmSync(assetsDirectory, { recursive: true, force: true });
199
+ sides[side] = {
200
+ label: side === 'baseline' ? snapshots.baselineLabel : snapshots.currentLabel,
201
+ commit: side === 'baseline' ? snapshots.baselineCommit : snapshots.currentCommit,
202
+ branch: side === 'current' ? snapshots.currentBranch : null,
203
+ dirty: side === 'current' && snapshots.currentDirty,
204
+ projectType: inspected[side].projectType, versions: inspected[side].versions,
205
+ packageManager: plan.packageManager, builtAt: new Date().toISOString(),
206
+ inputFingerprint: side === 'current' ? snapshots.snapshotHash : (0, crypto_1.createHash)('sha256').update(snapshots.baselineInputFingerprint).digest('hex'),
207
+ configFingerprint: configuration[side],
208
+ sourceContext: {
209
+ repositoryRoot: plan.snapshotRoot, projectRelativePath: relativeApp.split(path_1.default.sep).join('/'),
210
+ sourcesBase: inspected[side].sourceMapBase,
211
+ pathConvention: inspected[side].sourcePathConvention,
212
+ },
213
+ };
214
+ console.log(chalk_1.default.green(`✓ Generated ${side} bundle, matching source map and inventory of ${assetEntries[side].length} emitted assets`));
215
+ }
216
+ artifacts = {
217
+ ...pairs, outputDirectory: directory, metadataPath: path_1.default.join(directory, 'comparison.json'),
218
+ assetManifestPath: path_1.default.join(directory, 'comparison-assets.json'),
219
+ };
220
+ (0, assets_1.writeComparisonAssetManifest)(artifacts.assetManifestPath, {
221
+ version: 1, metric: 'emitted-asset-bytes', ...assetEntries, ota,
222
+ });
223
+ const warnings = [
224
+ 'Both builds use detached HEAD; original staging partitions are not reproduced.',
225
+ ...(JSON.stringify(baseline.versions) !== JSON.stringify(current.versions) ? ['Framework or bundler versions differ between builds.'] : []),
226
+ ...(sides.baseline.configFingerprint !== sides.current.configFingerprint ? ['Dependency or build configuration inputs differ between builds.'] : []),
227
+ ];
228
+ (0, metadata_1.writeComparisonMetadata)(artifacts, {
229
+ version: 2, mode: 'compare', metric: 'javascript-utf8-bytes',
230
+ settings: { platform, dev: false, minify: true, nodeVersion: process.version, entryPoint: current.entry },
231
+ ...sides, includedPaths: snapshots.includedPaths, warnings,
232
+ });
233
+ complete = true;
234
+ const shouldOpen = options.open !== false && process.stdin.isTTY && (await (0, prompts_1.default)({
235
+ type: 'confirm', name: 'openSight', message: 'Open Bundle Drop Sight and start the local comparison?', initial: true,
236
+ })).openSight === true;
237
+ controller.signal.throwIfAborted();
238
+ if (!shouldOpen) {
239
+ manualInstructions(artifacts);
240
+ succeeded = true;
241
+ return;
242
+ }
243
+ const session = await (0, sight_session_1.startSightSession)({
244
+ comparison: artifacts, sightPageUrl: process.env.BUNDLE_DROP_SIGHT_URL || SIGHT_URL, signal: controller.signal,
245
+ });
246
+ try {
247
+ try {
248
+ await (0, sight_session_1.openSightInBrowser)(session.sightUrl);
249
+ }
250
+ catch {
251
+ console.log(chalk_1.default.yellow(`Open this one-time URL manually:\n${session.sightUrl}`));
252
+ }
253
+ await session.waitForTransfer();
254
+ console.log(chalk_1.default.green('✓ Comparison files loaded into Sight'));
255
+ if (!options.keep && !options.output)
256
+ fs_1.default.rmSync(directory, { recursive: true, force: true });
257
+ else
258
+ manualInstructions(artifacts);
259
+ }
260
+ finally {
261
+ await session.close();
262
+ }
263
+ succeeded = true;
264
+ }
265
+ catch (error) {
266
+ if (complete && artifacts)
267
+ manualInstructions(artifacts);
268
+ console.error(`Comparison diagnostics: ${diagnostics}`);
269
+ throw error;
270
+ }
271
+ finally {
272
+ process.removeListener('SIGINT', cancel);
273
+ process.removeListener('SIGTERM', cancel);
274
+ try {
275
+ await snapshots?.cleanup();
276
+ }
277
+ catch (error) {
278
+ const message = `Could not remove comparison worktrees at ${snapshots?.directory}: ${String(error)}`;
279
+ console.error(message);
280
+ if (succeeded) {
281
+ console.error(`Comparison diagnostics: ${diagnostics}`);
282
+ throw new Error(message);
283
+ }
284
+ }
285
+ if (!complete && directory && !options.output)
286
+ fs_1.default.rmSync(directory, { recursive: true, force: true });
287
+ if (succeeded)
288
+ fs_1.default.rmSync(diagnostics, { recursive: true, force: true });
289
+ }
290
+ }
@@ -0,0 +1,26 @@
1
+ export type ComparisonSnapshotOptions = {
2
+ projectRoot: string;
3
+ compareRef: string;
4
+ fetch?: boolean;
5
+ include?: string[];
6
+ signal?: AbortSignal;
7
+ };
8
+ export type ComparisonSnapshots = {
9
+ directory: string;
10
+ currentRoot: string;
11
+ baselineRoot: string;
12
+ currentProjectRoot: string;
13
+ baselineProjectRoot: string;
14
+ currentCommit: string;
15
+ baselineCommit: string;
16
+ currentLabel: string;
17
+ baselineLabel: string;
18
+ currentBranch: string | null;
19
+ currentDirty: boolean;
20
+ snapshotHash: string;
21
+ baselineInputFingerprint: string;
22
+ includedPaths: string[];
23
+ assertIdentity: () => Promise<void>;
24
+ cleanup: () => Promise<void>;
25
+ };
26
+ export declare function createComparisonSnapshots(options: ComparisonSnapshotOptions): Promise<ComparisonSnapshots>;